Mysql keeps entering blank fields, can anyone help me fix this?
I'm trying to learn php and mysql and its been going good but I'm trying to use the $_POST method to insert something to a database from another page, and when I check the database to see if it worked it creates another row but with no information.
First page
开发者_如何学C<html>
<body>
<form action="InsertExternal.php" method=post>
First Name: <input type="text" name="firstname" />
Last Name: <input type="text" name="lastname" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
</body>
Second page
<?php
$con = mysql_connect("localhost","root","root");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("Learning", $con);
$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con)
?>
Thanks for any help. I imagine its something simple I'm missing.
Make sure you are not contacting this page directly. In this case before doing the actual insert check if there are values in the fields:
if(isset($_POST['firstname']) && isset($_POST['lastname']) && ..
Second thing, You must sanitize your input before inserting into the database: use:
$firstname = mysql_real_esacpe_string($_POST['firstname']);
You can also use or with in the statement:
mysql_query($q)
or die(mysql_error());
You are never checking if the form was submitted on the second page, nothing "huge" but it could just be that a refresh is occuring and empty data is going in. Second, you will should really change the insert portion up so you do not get a ton of "Undefined Constant notices" from not surrounding the associative indexed $_POST
array with single quotes.
<?php
if (empty($_POST['age'])) {
echo "Sorry, you appear to have omitted a few items. Try again!";
exit;
}
$con = mysql_connect("localhost","root","root");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("Learning", $con);
$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES
('{$_POST['firstname']}','{$_POST['lastname']}','{$_POST['age']}')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con)
?>
There is also the obvious worry of SQL Injection, if you plan on really wanting to use MySQL that is a topic you should read up on and learn the proper methods to prevent it.
<?php
$con = mysql_connect("localhost","root","root");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("Learning", $con);
$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES
('" . $_POST["firstname"] . "','" . $_POST["lastname"] . "','" . $_POST["age"] . "')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con)
?>
Didnt quote the globals properly
精彩评论