Need help with undefined index error message

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Tokunbo
Forum Commoner
Posts: 46
Joined: Thu Sep 29, 2011 8:53 am

Need help with undefined index error message

Post by Tokunbo »

hello sirs,

kindly, what is wrong with this my code.

The error message prompt on line 15 is this line:
$sql="INSERT INTO Contacts (Surnname, Firstname) VALUES('$_POST[sname]','$_POST[fname]')";

My db connection and table selection are ok. however when I click on the this file(combined2.php), I can see the below error messages above the form. Do I need to predefine sname and fname as something at the start of the code?

the error message is:
Notice: Undefined index: sname in C:\wamp\www\DBdisplay\combined2.php on line 15
Notice: Undefined index: fname in C:\wamp\www\DBdisplay\combined2.php on line 15

Code: Select all

<html>
<body>

<?php
//mysql connection
$con = mysql_connect("localhost","username","password");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
//select db
mysql_select_db("contactdb1", $con);

//add record
$sql="INSERT INTO Contacts (Surnname, Firstname) VALUES('$_POST[sname]','$_POST[fname]')";

if (!mysql_query($sql,$con))
  {
  die('Error: ' . mysql_error());
  }
?>


<form name="form1" action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
    Surnname: <input type="text" name="sname" />
	Firstname: <input type="text" name="fname" />
    <input type="submit" name="btnSendForm" value="Send" />
</form>

</body>
</html> 

User avatar
twinedev
Forum Regular
Posts: 984
Joined: Tue Sep 28, 2010 11:41 am
Location: Columbus, Ohio

Re: Need help with undefined index error message

Post by twinedev »

Well, your code as is, will ALWAYS attempt an insert, no matter if you submitted the form, or it is the first time coming to the page. So, I'm guessing you are getting this when you first hit the page before you actually submit anything.

1. you need to use an if statement to make sure the form was submitted

2. You should also use the mysql_real_escape_string() to wrap the values, never trust anything a user can submit.

3. need to do $_POST['sname'] instead of $_POST[sname] (see http://us3.php.net/manual/en/language.t ... rray.donts for why)

Sample code I would do based upon what you have:

Code: Select all

<?php

	$con = mysql_connect("localhost","username","password")
		or die ('ERR: Could not connect to server. '.mysql_error());

	mysql_select_db('contractdb1',$con)
		or die ('ERR: Could not use database. '.mysql_error());


	if (count($_POST)>0 && isset($_POST['sname']) && isset($_POST['fname'])) {

		// FORM WAS SUBMITTED

		$SQL  = 'INSERT INTO `Contracts` (`Surname`,`Firstname`) VALUES (';
		$SQL .= '"'.mysql_real_escape_string($_POST['sname']).'",';
		$SQL .= '"'.mysql_real_escape_string($_POST['fname']).'")';
		
		mysql_query($SQL)
			or die ('ERR: Could not write data. '.mysql_error());

	}

?><html>
<body>
	<form name="form1" action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
		Surnname: <input type="text" name="sname" />
		Firstname: <input type="text" name="fname" />
		<input type="submit" name="btnSendForm" value="Send" />
	</form>
</body>
</html>
Tokunbo
Forum Commoner
Posts: 46
Joined: Thu Sep 29, 2011 8:53 am

Re: Need help with undefined index error message

Post by Tokunbo »

@twinedev,

thanks for the help.

I am now able to display my form inputs on the same page. Now what I want to do is to have a submit button beside each displayed data that would allow it to be deleted. Can you please advise how I can go about this:

heres the entire code

Code: Select all

<html
<body

<form action="home.php" method="post" enctype="application/x-www-form-urlencoded" name="form1">
<table width="252" border="1">
  <tr>
    <th width="103" scope="col">Surnname</th>
    <th width="280" scope="col"><input type="text" name="sname" id="sname"></th>
  </tr>
  <tr>
    <th scope="col">Firstname</th>
    <th scope="col"><input type="text" name="fname" id="fname"></th>
  </tr>
  <tr>
    <th scope="col">&nbsp;</th>
    <th scope="col"><input type="submit" name="submit" id="submit" value="Submit"></th>
  </tr>
</table>

</form>

<?php
//connect to db
        $con = mysql_connect("localhost","tokunbo","tokunbo")
                or die ('ERR: Could not connect to server. '.mysql_error());
//select db
        mysql_select_db('contactdb1',$con)
                or die ('ERR: Could not use database. '.mysql_error());

//insert record
        if (count($_POST)>0 && isset($_POST['sname']) && isset($_POST['fname'])) {

                // FORM WAS SUBMITTED

                $SQL  = 'INSERT INTO `contacts` (`Surnname`,`Firstname`) VALUES (';
                $SQL .= '"'.mysql_real_escape_string($_POST['sname']).'",';
                $SQL .= '"'.mysql_real_escape_string($_POST['fname']).'")';
               
                mysql_query($SQL)
                        or die ('ERR: Could not write data. '.mysql_error());
        }

//display record
print "<table width='60%' border='1'>";

$query="SELECT * FROM contacts";
$result=mysql_query($query);
$num=mysql_numrows($result);

?>

<?php
$i=0;
while ($i < $num) {
$field1name=mysql_result($result,$i,"Surnname");
$field2name=mysql_result($result,$i,"Firstname");
print "<tr><td>$field1name.$field2name</td></tr>";
?>


<?php
$i++;
}
?>



</body>
</html>
User avatar
amirbwb
Forum Commoner
Posts: 89
Joined: Sat Oct 30, 2010 6:10 pm

Re: Need help with undefined index error message

Post by amirbwb »

Me 2 I a m getting :
Notice: Undefined index: test in C:\xampp\htdocs\training\index.php on line 2
here is the code:

Code: Select all

<?php
$test=$_POST['test'];
echo $test;
?>
I tried this on my second pc and it works correctly without any error ??!! what to do ??
User avatar
flying_circus
Forum Regular
Posts: 732
Joined: Wed Mar 05, 2008 10:23 pm
Location: Sunriver, OR

Re: Need help with undefined index error message

Post by flying_circus »

amirbwb wrote:Me 2 I a m getting :
Notice: Undefined index: test in C:\xampp\htdocs\training\index.php on line 2
here is the code:

Code: Select all

<?php
$test=$_POST['test'];
echo $test;
?>
I tried this on my second pc and it works correctly without any error ??!! what to do ??
The reason the error is thrown on one computer and not the other is likely a difference in error reporting settings within the php.ini.

Either way, the error is telling you whats going on. "Notice: Undefined index: test in C:\xampp\htdocs\training\index.php on line 2".

So we look at line 2 of index.php, where the index 'test' ($text) is defined, and we find that: $test=$_POST['test'];

I would go out on a limb and suggest that you are referencing the post variable 'test', but it does not exist, either the page request was not a POST (likely a GET), or the POST that you submitted, does not contain the variable 'test'.

How do we fix this, the right way?

Lucky for all of us, it's rather easy and straight forward.

ALWAYS remember this rule of thumb, check a variables existance before referencing it. It is very easy to do with the ternary operator (http://www.php.net/manual/en/language.o ... on.ternary)

Code: Select all

$test = isset($_POST['test']) ? $_POST['test'] : '';
The above statement checks to see if the post var 'test' is set, if it is, then we set $test to $_POST['test']. If it is not set, then $test will equal ''.

Please get in the habit of doing this, it will only make you a better programmer!
User avatar
amirbwb
Forum Commoner
Posts: 89
Joined: Sat Oct 30, 2010 6:10 pm

Re: Need help with undefined index error message

Post by amirbwb »

I have been using php for more than 2 years, and it's the first time that I see this notification ... this is weird, anyway thank you
Tokunbo
Forum Commoner
Posts: 46
Joined: Thu Sep 29, 2011 8:53 am

Re: Need help with undefined index error message

Post by Tokunbo »

@Flying_circus,

thanks for the clarification. Re the line:

Code: Select all

$test = isset($_POST['test']) ? $_POST['test'] : '';
will this evaluate as a normal" If isset" statement below?

Code: Select all

if !(isset($test)) {
    $test=$_POST['test'];
}
as in checking if its not set, then if its not set, we set it to post(test)?
or maybe Im mixing things up. pls clarify
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Need help with undefined index error message

Post by Celauran »

Tokunbo wrote:will this evaluate as a normal" If isset" statement below?

Code: Select all

if !(isset($test)) {
    $test=$_POST['test'];
}
as in checking if its not set, then if its not set, we set it to post(test)?
or maybe Im mixing things up. pls clarify
You've got it backwards. You're getting the notice (it's not an error) because $_POST['test'] is potentially not set when you're trying to assign its value to $test.

Code: Select all

$test = '';
if (isset($_POST['test']))
{
    $test = $_POST['test'];
}
Clearly, using the ternary operator keeps things neater.
Post Reply