Undefined Index Notice
Posted by: iDread (66.158.199.---)
Date: August 31, 2009 02:29AM

I've built a form that will accept a name and number (not validated yet) and then display that name and number along with every other record from the table. When I load the page I get :

Notice: Undefined index: uName in C:\wamp\www\tutorial\postTest.php on line 20

Notice: Undefined index: uNum in C:\wamp\www\tutorial\postTest.php on line 20

and a blank record is inserted and displayed... ?!? The form also appears and works perfectly but I'm sure this notice shouldn't be here. I've read about suppressing notices and that isn't what I want to do. I'd like to correct my code so this isn't an issue. I'm VERY new to php so please include code examples with any response. Thanks in advance.

here is my code:

include("myformtest.html" );
include("db_con.php" );

if (!$con) {
die('Could not connect: ' . mysql_error());
}

mysql_select_db($db, $con);

$sql = "INSERT INTO testTable (uName, uNum) VALUES ('$_POST[uName]', '$_POST[uNum]')";

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

$result = mysql_query("SELECT * FROM testTable" );

echo ("<table border='1'>" );

while($row = mysql_fetch_array($result)){
echo "<tr>";
echo ("<td>" . $row['uName'] . "</td><td>" . $row['uNum'] . "</td><td>" . $row['postdate'] . "</td>" );
echo "</tr>";
}

echo("</table>" );

mysql_close($con);


my environment:
wampserver2
php 5.2.9
mysql 5.1.36
apache 2.2.11

Dread

Re: Undefined Index Notice
Posted by: c2dan (---.15-1.cable.virginmedia.com)
Date: August 31, 2009 03:22PM

This is not a a form help with code, but I'll help anyway

Is a form being posted to that script? If it is you should only execute these lines of code
$sql = "INSERT INTO testTable (uName, uNum) VALUES ('$_POST[uName]', '$_POST[uNum]')";

if (!mysql_query($sql,$con)){
die('Error: ' . mysql_error());
}
When the form is submitted.

Otherwise a blank record will be added to your tetsTable as the $_POST variables do not exists yet. The most common way to achieve this is to name your submit button in your form as submit. Now change the above lines I mentioned to


[php]// check that form is submitted
if(isset($_POST['submit'])) {
$sql = "INSERT INTO testTable (uName, uNum) VALUES ('$_POST[uName]', '$_POST[uNum]')";

if (!mysql_query($sql,$con)){
die('Error: ' . mysql_error());
}
}[/php]
Now a record will only be added when the form is submitted.

Re: Undefined Index Notice
Posted by: iDread (66.158.199.---)
Date: August 31, 2009 11:35PM

@c2dan

Sorry, I didn't mean to intrude. I wasn't sure where else to go. Thanks for letting me know and bearing with me though. Any suggestions on php support forums?

Yes, a form is posted to this script. I just used 'include' rather than actually putting the form on the same page. I've read this is good practice...

And thanks a ton! That worked superbly!

Dread

Sorry, only registered users may post in this forum.