You'll see the Undefined Index error messages when you load the page for the first time.
To fix the errors, use isset()
and check if the form was actually submitted:
if(isset($_POST['submit'])) {
print_r($_POST); //to see all the form inputs
// your code ...
}
I'd also check if the variables are set:
$foodname = (isset($_POST['food_name'])) ? $_POST['food_name'] : NULL;
$calories = (isset($_POST['calories'])) ? $_POST['calories'] : NULL;
$healthy = (isset($_POST['healthy_unhealthy'])) ? $_POST['healthy_unhealthy'] : NULL;
Unrelated sidenote: Your code is vulnerable to SQL injection. Instead of directly inserting the variables in your MySQL query, escape them first using mysql_real_escape_string()
, like so:
$foodname = mysql_real_escape_string($foodname);
$calories = mysql_real_escape_string($calories);
$healthy = mysql_real_escape_string($healthy);
That'd help prevent SQL injection. Better yet, stop using the mysql_*
functions. They are no longer maintained and are officially deprecated. Learn about prepared statements instead, and use PDO or MySQLi.
With the corrections, your code should look like:
if(isset($_POST['submit']))
{
/* form was submitted, proceed */
$submit_button = $_POST['submit'];
/* checking if user inputs are set */
$foodname = (isset($_POST['food_name'])) ? $_POST['food_name'] : NULL;
$calories = (isset($_POST['calories'])) ? $_POST['calories'] : NULL;
$healthy = (isset($_POST['healthy_unhealthy'])) ? $_POST['healthy_unhealthy'] : NULL;
/* escaping user inputs */
$foodname = mysql_real_escape_string($foodname);
$calories = mysql_real_escape_string($calories);
$healthy = mysql_real_escape_string($healthy);
//query
$sql="INSERT INTO `food` (`food`, `calories`, `healthy_unhealthy`) VALUES('$foodname', '$calories', '$healthy')";
/* storing query result to a variable */
$result = mysql_query($sql, $conn);
if($result)
{
//do stuff
}
else
{
die(mysql_error()); //display error, and exit
}
}
Hope this helps!