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
<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:
Second thing,
You must sanitize your input before inserting into the database:
use:
You can also use or with in the statement: