1

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>
Diego C Nascimento
  • 2,801
  • 1
  • 17
  • 23
joebegborg07
  • 821
  • 3
  • 14
  • 27
  • the code is in insert.php? – Gonzalo.- Sep 16 '13 at 19:16
  • what data has been posted to your script? – Liam Sorsby Sep 16 '13 at 19:16
  • `$foo = array('bar'); $foo['fake'];` That's what causes that notice. – Mike B Sep 16 '13 at 19:16
  • I'm not sure I understand what you mean there. – joebegborg07 Sep 16 '13 at 19:17
  • 2
    I think you just get the warning the first time you request your page. Since at that time nobody has POSTed the form and so the $_POST array is empty. I guess after you submit your form the warning is gone? – hagbard Sep 16 '13 at 19:17
  • basically, no data has been passed to them variables, try using var_dump($_POST) and see what has been posted – Liam Sorsby Sep 16 '13 at 19:18
  • Yes the error is just the first time I load the page. Can I just hide the error using @ or is this error slightly more serious than that? – joebegborg07 Sep 16 '13 at 19:20
  • 1
    Red alert! Possible SQL-injection! [Read all about it, here!](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php?rq=1) – Marty McVry Sep 16 '13 at 19:20
  • Using `@` to suppress the error message is generally a bad idea. Instead, find out why the message comes and add checks to prevent the error. In this case, check whether or not the array index exists before reading its value. – Arjan Sep 16 '13 at 19:24
  • @user2612009 Your best bet is to fix it at the source and use `if(isset($_POST['submit'])) {` as shown from the answers given to you below. And don't suppress errors with the `@` symbol for probable important information when errors occur. – Funk Forty Niner Sep 16 '13 at 19:27

6 Answers6

3

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.

Julio
  • 2,261
  • 4
  • 30
  • 56
  • Not sure if this helps but I'm only getting this error the first time I run the page. By the way thanks for all the help so far :). – joebegborg07 Sep 16 '13 at 19:26
  • @user2612009 then you're going to want to verify that you're currently in the "expecting POST data" state. To do this, see the first part of my answer (with the update). – Julio Sep 16 '13 at 19:29
  • Thanks man :) wrapping my code in the if(isset($_POST['submit']; Did the trick :) – joebegborg07 Sep 16 '13 at 19:33
2

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);
Cleiton Souza
  • 811
  • 1
  • 10
  • 21
1

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!

Amal Murali
  • 75,622
  • 18
  • 128
  • 150
1

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.

Bart Friederichs
  • 33,050
  • 15
  • 95
  • 195
0

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);
    }
}
The Alpha
  • 143,660
  • 29
  • 287
  • 307
0

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:

  • Don't use the mysql extension. It has been deprecated, use mysqli or pdo:mysql instead.
  • Sanitize your variables before using them (p.e. using mysqli_real_escape_string or, even better, work with prepared statements.
Bjoern
  • 15,934
  • 4
  • 43
  • 48