Solved

Insert into database, php/sql not working

Posted on 2010-09-22
22
409 Views
Last Modified: 2013-12-12
I have an insert.php page where the user will enter 3 things and i have the action set to the doInsert.php page.  When i enter information into the fields the doInsert page runs and returns the user to the select.php page but there is no additional information entered into the database.  The select page is working and shows the information coming from the database in the tables i made, so it must be the doInsert.php can anyone help me to narrow it down, i am fairly new to using php.
<?php

session_start();

include("includes/openDbConn.php");

$shipperID		= $HTTP_POST_VARS["shipperID"];
$companyName	= $HTTP_POST_VARS["companyName"];
$phone			= $HTTP_POST_VARS["phone"];

if(empty($shipperID))
	header("Location: insert.php");
	
$sql = "INSERT INTO ShipppersLab6(ShipperID, CompanyName, Phone)";
$sql = $sql." VALUES(".$shipperID.", ";
$sql = $sql."'".$companyName."', '".$phone."')";


$result = mysql_query($sql);

include("includes/closeDbConn.php");

header("Location: select.php");

?>

Open in new window

<?php 

session_start();

if(empty($SESSION["errorMessage"]))
	$_SESSION["errorMessage"] = "";

echo("<?xml version=\"1.0\" encoding=\"UTF-8\"?");?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; UTF-8" />
<title>This is Insert Page</title>
<style type="text/css">
	form { width: 400px; }
	ul{ list-style:none; margin-top: 5px;}
	ul li { display:block; float: left; width: 100%; height: 3%;}
	ul li label { float: left; padding: 7px; }
	ul li input, ul li textarea { float: right; margin-right: 10px; border: 1px solid #000; padding: 3px; width: 60%;}
</style>
</head>

<body>
<h1>Insert Page</h1>

<?php include ("includes/menu.php"); ?>

<form id="form0" method="post" action="doInsert.php">
	<ul>
    	<li><label for="shipperID">Shipper ID</label>
        <input name="shipperID" id="shipperID" type="text" size="20" maxlength="3"/></li>
        
        <li><label for="companyName">Company Name</label>
        <input name="companyName" id="companyName" type="text" size="20" maxlength="20"/></li>
        
        <li><label for="phone">Phone</label>
        <input name="phone" id="phone" type="text" size="20" maxlength="20"/></li>
        
        <li><?php echo $_SESSION["errorMessage"]; ?></li>
        <li><input type="submit" value="Insert Info" name="submit"/></li>
    </ul>
</form>

<script type="text/javascript">
	document.getElementById("shipperID").focus();
</script>

</body>
</html>

Open in new window

0
Comment
Question by:newmie22
  • 8
  • 7
  • 6
  • +1
22 Comments
 
LVL 58

Expert Comment

by:cyberkiwi
ID: 33739618
In doInsert, line 19, try this

$result = mysql_query($sql) or die(mysql_error());
0
 
LVL 58

Expert Comment

by:cyberkiwi
ID: 33739622
or

$result = mysql_query($sql) or die($sql . "<br>" . mysql_error());
0
 

Author Comment

by:newmie22
ID: 33739711
I used both.  When fill in text for each of the 3 boxes and hit insert i get brought back to the insert.php page with cleared fields. But nothing gets inserted into the database
0
 
LVL 7

Expert Comment

by:ziceva
ID: 33739758
If you are brought back to the insert.php page, it means that the

if(empty($shipperID))
      header("Location: insert.php");

part get's executed ... so, the shipperID does not get set.
If you are using PHP 4.1 or later, you should really switch to using $_POST instead of $HTTP_POST_VARS
0
 
LVL 58

Expert Comment

by:cyberkiwi
ID: 33739766
At the risk of sounding silly, please give this a try.
<?php



session_start();



include("includes/openDbConn.php");



$shipperID		= $HTTP_POST_VARS["shipperID"];

$companyName	= $HTTP_POST_VARS["companyName"];

$phone			= $HTTP_POST_VARS["phone"];



if(empty($shipperID))

	header("Location: insert.php");

	

$sql = "INSERT INTO ShipppersLab6(ShipperID, CompanyName, Phone)";

$sql = $sql." VALUES(".$shipperID.", ";

$sql = $sql."'".$companyName."', '".$phone."')";



//$result = mysql_query($sql);

$result = mysql_query($sql) or die($sql . "<br>" . mysql_error());



$rows = mysql_query("select Count(*) from ShipppersLab6") or die(mysql_error());



var_dump( $rows );



include("includes/closeDbConn.php");



//header("Location: select.php");



?>

Open in new window

0
 
LVL 58

Expert Comment

by:cyberkiwi
ID: 33739770
Or better
<?php



session_start();



include("includes/openDbConn.php");



$shipperID		= $HTTP_POST_VARS["shipperID"];

$companyName	= $HTTP_POST_VARS["companyName"];

$phone			= $HTTP_POST_VARS["phone"];



if(empty($shipperID))

	header("Location: insert.php");

	

$sql = "INSERT INTO ShipppersLab6(ShipperID, CompanyName, Phone)";

$sql = $sql." VALUES(".$shipperID.", ";

$sql = $sql."'".$companyName."', '".$phone."')";



//$result = mysql_query($sql);

$result = mysql_query($sql) or die($sql . "<br>" . mysql_error());



$rows = mysql_query("select Count(*) from ShipppersLab6") or die(mysql_error());



var_dump( $sql );

var_dump( $rows );



include("includes/closeDbConn.php");



//header("Location: select.php");



?>

Open in new window

0
 
LVL 13

Expert Comment

by:p_nuts
ID: 33739780
why dont you put ..

echo '
';
print_r($_REQUEST);
echo '

Open in new window

';

at the start of the script. that will show you whats been send.

also remove the

if(empty($shipperID))
      header("Location: insert.php");

or change it to

if(empty($shipperID))
      echo 'noshipper';

we can later turn that back.
0
 

Author Comment

by:newmie22
ID: 33739795
p nuts: when i enter that and then remove the

if(empty($shipperID))
      header("Location: insert.php");

and comment out the header("Location: select.php");

i get this:

Array
(
    [shipperID] => 4
    [companyName] => testing
    [phone] => testing
    [submit] => Insert Info
    [PHPSESSID] => ctfvbig9mv2cjpj70sra2m7jv0
)
0
 

Author Comment

by:newmie22
ID: 33739807
cyberwiki when i use your second set of code i get brought back to insert.php when i comment out the if statement that brings me there i and then try to insert something i get:

INSERT INTO ShipppersLab6(ShipperID, CompanyName, Phone) VALUES(, '', '')
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' '', '')' at line 1
0
 
LVL 58

Expert Comment

by:cyberkiwi
ID: 33739863
As ziceva has stated:

you should really switch to using $_POST instead of $HTTP_POST_VARS

$shipperID            = $_POST["shipperID"];
$companyName      = $_POST["companyName"];
$phone                  = $_POST["phone"];
0
 
LVL 7

Expert Comment

by:ziceva
ID: 33739865
First of all, replace
$sql = $sql." VALUES(".$shipperID.", ";
with
$sql = $sql." VALUES('".$shipperID."', ";
and the mysql error will go away ...

Next you need to figure out why the POST variables are not set correctly ...
0
Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

 

Author Comment

by:newmie22
ID: 33739924
I appreciate everyone's help, we just started learning this, so even small things become troubleshooting for me.  I was only using HTTP_POST_VARS because that's how we'd learned it, i switched to just _POST and fixed the mysql error ziceva noticed.

If i comment out the header to take me back to select.php when i insert something i get brought to a my blank doInsert.php page, I can't figure out why it's not passing the variables.
0
 
LVL 7

Expert Comment

by:ziceva
ID: 33739941
Please comment out the header that redirects to select.php and add this line after session_start():

print_r($_POST);

And tell us what the output is.
0
 

Author Comment

by:newmie22
ID: 33739944
Array ( [shipperID] => 6 [companyName] => Testing [phone] => Testing [submit] => Insert Info )
0
 
LVL 7

Expert Comment

by:ziceva
ID: 33739968
Ok, that is very good ... all the data is in place ...
Try this for the doInsert.php

<?php

session_start();

include("includes/openDbConn.php");

$shipperID            = $_POST["shipperID"];
$companyName      = $_POST["companyName"];
$phone                  = $_POST["phone"];

if(empty($shipperID))
      header("Location: insert.php");
      
$sql = "INSERT INTO ShipppersLab6 (ShipperID, CompanyName, Phone)";
$sql .= "VALUES ('$shipperID','$companyName','$phone')";

$result = mysql_query($sql);

include("includes/closeDbConn.php");

header("Location: select.php");

?>
0
 
LVL 7

Expert Comment

by:ziceva
ID: 33739973
You should put a space before VALUES like so:

$sql .= " VALUES ('$shipperID','$companyName','$phone')";
0
 

Author Comment

by:newmie22
ID: 33739989
It goes through the doInsert.php page and brings me back to select.php but still not inserted any information into the database.  I open the database manually through phpMyAdmin and i can see no values are being inserted into the tables.
0
 
LVL 7

Expert Comment

by:ziceva
ID: 33740003
One more try:

<?php

session_start();

include("includes/openDbConn.php");

if(empty($shipperID))
      header("Location: insert.php");
     
$sql = "INSERT INTO ShipppersLab6 (ShipperID, CompanyName, Phone)";
$sql .= "VALUES ('".$_POST["shipperID"]."','".$_POST["companyName"]."','".$_POST["phone"]."')";

$result = mysql_query($sql);

include("includes/closeDbConn.php");

header("Location: select.php");

?>
0
 
LVL 7

Accepted Solution

by:
ziceva earned 500 total points
ID: 33740012
Damn ... made the same mistake ... It should be:

$sql .= " VALUES ('".$_POST["shipperID"]."','".$_POST["companyName"]."','".$_POST["phone"]."')";
0
 

Author Closing Comment

by:newmie22
ID: 33740024
Thanks a bunch man that got it to work! I appreciate all the help!
0
 
LVL 58

Expert Comment

by:cyberkiwi
ID: 33740029
Make the fix in http:#a33739863 against the code in http:#33739770

Now what do you get?
The 2 var_dumps are worth their weight in gold.

If you run it a few times and the count(*) doesn't go up, you have other problems.
If it does, then your select may not be looking at the same data that you are inserting into.
0
 
LVL 7

Expert Comment

by:ziceva
ID: 33740046
Now, to make it safer, u can use this:

$sql .= " VALUES ('".mysql_real_escape_string($_POST["shipperID"])."','".mysql_real_escape_string($_POST["companyName"])."','".mysql_real_escape_string($_POST["phone"])."')";

If you want to know why is that safer, read about Sql Injection ...
0

Featured Post

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Introduction Many web sites contain image galleries; a common design for these galleries includes a page with a collection of thumbnail images.  You can click on each of the thumbnail images to see the larger version of the image.  This is easily i…
Author Note: Since this E-E article was originally written, years ago, formal testing has come into common use in the world of PHP.  PHPUnit (http://en.wikipedia.org/wiki/PHPUnit) and similar technologies have enjoyed wide adoption, making it possib…
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to dynamically set the form action using jQuery.

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now