This question already has an answer here:
I'm still a beginner to php and I cannot seem to understand what's wrong here. The code still works even though there's an 'unidentified index' error. The error I get would be referring to the variables $food, $calories, $healthy, $submit.
The code is:
<?php
require 'connect.inc.php';
$foodname = $_POST['food_name'];
$calories = $_POST['calories'];
$healthy = $_POST['healthy_unhealthy'];
$submit_button = $_POST['submit'];
$sql="INSERT INTO `food` (`food`, `calories`, `healthy_unhealthy`) VALUES('$foodname', '$calories', '$healthy')";
if(isset($submit_button)&&!empty($foodname)&&!empty($calories)&&!empty($healthy))
{
mysql_query($sql, $conn);
}
else{
echo'Kindly fill in fields';
}
?>
<form action="insert.php" method="POST">
Food Name:<br>
<input type="text" name="food_name"><br>
Calories:<br>
<input type="text" name="calories"><br>
Healthy:<br>
<input type="text" name="healthy_unhealthy"><br>
<input type="submit" name="submit">
</form>
</div>
First and foremost, ensure that you're in the appropriate state to be accepting the data. Wrap your code in an:
<?php
require 'connect.inc.php';
// We only run this code if the user has POSTed data to this page. Without this we
// will get an 'undefined index' error.
if(isset($_POST['submit'])) {
$foodname = $_POST['food_name'];
$calories = $_POST['calories'];
$healthy = $_POST['healthy_unhealthy'];
$submit_button = $_POST['submit'];
$sql="INSERT INTO `food` (`food`, `calories`, `healthy_unhealthy`) VALUES('$foodname', '$calories', '$healthy')";
if(isset($submit_button)&&!empty($foodname)&&!empty($calories)&&!empty($healthy))
{
mysql_query($sql, $conn);
}
else{
echo'Kindly fill in fields';
}
}
?>
<form action="insert.php" method="POST">
Food Name:<br>
<input type="text" name="food_name"><br>
Calories:<br>
<input type="text" name="calories"><br>
Healthy:<br>
<input type="text" name="healthy_unhealthy"><br>
<input type="submit" name="submit">
</form>
This will ensure that you're currently receiving a POST request, from the form you've defined.
The $_POST variable is an array containing data you've sent to the web application via a POST request. In your form you should have fields with the appropriate names (food_name, calories, healthy_unhealthy, etc). It sounds like these fields may be missing.
In your code, somewhere near the top, put in the following:
print_r($_POST);
or, alternatively you could do a
var_dump($_POST);
This will print out the contents of your $_POST variable. If you do not see any reference to food_name, calories, or healthy_unhealthy check that your form is correct and is passing these variables to the web application.
try put a wrapper in ur php... like this:
if (isset($_POST['submit'])) {
//code here....
}
and alter ur form to this:
<form action="" method="POST">
to debug.. use this:
var_dump($toDebug);
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!
PHP allows you to use undefined or undeclared variables. When you refer to a variable that is never declared, you get this notice.
When an unidentified variable is encountered, it takes the default "zero" value for the deducted type. 0 in case for numbers, or an empty string for strings.
In your case, the $_POST
variable isn't filled with values (they are filled by POSTing a form), and you get a notice for each unidentified variable.
More can be found in the documentation:
It is not necessary to initialize variables in PHP however it is a very good practice. Uninitialized variables have a default value of their type depending on the context in which they are used - booleans default to FALSE, integers and floats default to zero, strings (e.g. used in echo) are set as an empty string and arrays become to an empty array.
Whether or not this is a smart language design decision, I'll leave to yourself.
You have this code
$sql="INSERT INTO `food` (`food`, `calories`, `healthy_unhealthy`) VALUES('$foodname', '$calories', '$healthy')";
if(isset($submit_button)&&!empty($foodname)&&!empty($calories)&&!empty($healthy))
{
mysql_query($sql, $conn);
}
Where, you are using those variables outside of if
statement and first time those are not available, so, you can use, ($sql
variable should be populated inside the if statement)
if( isset($_POST['submit']) && (!empty($foodname) && !empty($calories) &&!empty($healthy)) ) {
$sql="INSERT INTO `food` (`food`, `calories`, `healthy_unhealthy`) VALUES('$foodname', '$calories', '$healthy')";
mysql_query($sql, $conn);
}
Also, you can use (better)
if( isset($_POST['submit']) ) {
$foodname = $_POST['food_name'];
$calories = $_POST['calories'];
$healthy = $_POST['healthy_unhealthy'];
if( !empty($foodname) && !empty($calories) && !empty($healthy) ){
$sql="INSERT INTO `food` (`food`, `calories`, `healthy_unhealthy`) VALUES('$foodname', '$calories', '$healthy')";
mysql_query($sql, $conn);
}
}
Unindentified index
is not an error, it is a notice. It doesn't stop your script, therefore it is continuing.
Keep in mind your $_POST
-variables might be empty, thats what causing this notice to appear. This itself isn't a problem, but you continue using this (now not properly initialized variables) in sql statements - which can have problematic consequences if not handles properly.
For debug purposed, do a quick var_dump($_POST);
to see what is in there.
You can avoid this using the isset()
function like this:
if (isset($_POST['food_name'])) {
//do something here
}
I tend to initialize my variables whenever i can, p.e. like this:
$food_name = (isset($_POST['food_name'])) ? $_POST['food_name'] : '' ;
This leads to a more problematic issue: SQL security. Coded like this, your script is heavily prone for sql injection attacks.
Two advices regarding this topic:
mysqli_real_escape_string
or, even better, work with prepared statements.