mastermike707 Posted August 2, 2006 Share Posted August 2, 2006 Uh, what causes undefined index errors? Is it sql related or session related? Link to comment https://forums.phpfreaks.com/topic/16391-undefined-index-errors/ Share on other sites More sharing options...
hitman6003 Posted August 2, 2006 Share Posted August 2, 2006 it means that you are referencing a variable that doesn't exist. It should be just a warning and not an error that would cause the script to stop running. Link to comment https://forums.phpfreaks.com/topic/16391-undefined-index-errors/#findComment-68210 Share on other sites More sharing options...
mastermike707 Posted August 3, 2006 Author Share Posted August 3, 2006 Can you give me a example of something that would cause this error and then the fixed version of that code. Thank you already. Link to comment https://forums.phpfreaks.com/topic/16391-undefined-index-errors/#findComment-68212 Share on other sites More sharing options...
wildteen88 Posted August 3, 2006 Share Posted August 3, 2006 A Simple example of this would be when using forms, the incorrect way:[code]<?php// get the users name:$name = $_POST['name'];// get the user age:$age = $_POST['age'];// display thier name and age:if($name != "" && $age != ""){ echo "Hello {$name}, you are {$age}"; echo "<br /><br />";}?><form action="" method="post"> Name: <input type="text" name="name" /><br /> Age: <input type="text" name="age" size="3" /> <input type="submit" value="Display Message" /></form>[/code]When you first run that code you'll get to undefined index messages:[quote]Notice: Undefined index: name in C:\server\www\test.php on line 4Notice: Undefined index: age in C:\server\www\test.php on line 7[/quote]Now the proper way:[code]<?php// check that form has been submitted:if(isset($_POST['submit'])){ // now that form has been submitted we can work with form variables $errors = ''; // check that form fields has been filled in: if(isset($_POST['name']) && !empty($_POST['name'])) { $name = $_POST['name']; } else { $errors[] = 'You have not filled in the name field'; } // check the age variable is numeric if(isset($_POST['age']) && is_numeric($_POST['age'])) { $age = $_POST['age']; } else { $errors[] = 'You have not filled in the age field correctly'; } // check there are no errors: if(is_array($errors)) { echo "Please correct the following errors:\n<ul>"; foreach($errors as $error) { echo "<li>{$error}</li>\n"; } echo "</ul>\n"; } else { echo "Hello {$name}, you are {$age}"; echo "<br /><br />"; }}?><form action="" method="post"> Name: <input type="text" name="name" /><br /> Age: <input type="text" name="age" size="3" /> <input type="submit" name="submit" value="Display Message" /></form>[/code] Link to comment https://forums.phpfreaks.com/topic/16391-undefined-index-errors/#findComment-68453 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.