Page 1 of 1

Question about form......

Posted: Mon Feb 10, 2003 2:33 pm
by Winter
Hello,
I am new user, and I plan to design a form with 3 columns, and all the values will be stored in database. Each of columns can be null. However, there is an error message comes up if one of the column is not filled in.
Please help !!! Thank you so much

Error message--------------------------------
Notice: Undefined index: bread in c:\inetpub\wwwroot\phptest\qultest.php on line 8

Form--------------------------------------------------
<html>
<body>
<form action=qultest.php method=post>
Your name: <input type=text name=name size=30><br>
Your gender: <input type=radio name=gender value=0>female
<input type=radio name=gender value=1>male<br>
favorive foods:<br>
<input type=checkbox name=bread value=1>bread<br>
<input type=checkbox name=fruit value=2>fruit<br>
<input type=checkbox name=candy value=3>candy<br>
<input type=submit name=submit value=submit>
</form>
</body></html>

qultest.php--------------------------------------
<?php
if ((!$_POST['name'])){
header ("Location: http://sunfire100/phptest/qultest_form.php");
exit;
}
$name=$_POST['name'];
$gender=$_POST['gender'];
$bread=$_POST['bread'];
$fruit=$_POST['fruit'];
$candy=$_POST['candy'];

$connection=mysql_connect("localhost","root","") or die("couldn't connect.");
$db=mysql_select_db("phptestdb",$connection) or dir("couldn't connect to database");
$sql="insert into test1 values( \"$name\",\"$gender\",\"$bread\",\"$fruit\",\"candy\")";
$result=mysql_query($sql,$connection) or die ("couldn't query");

?>

Winter :oops:

Posted: Mon Feb 10, 2003 2:47 pm
by daven
If you do not check a checkbox, it does not exist in the $_POST/$_GET arrays. So if you do not check "Bread" you cannot access $_POST['bread'] on the next page (same for all checkboxes). You need to check to see if the variable exists (isset($var) is designed for this).

Code: Select all

<?php
// $var = (condition)?option1:option2;
// this syntax is equivalent to:
// if(condition){option1;}
// else{option2;}
// chr(0) = NULL
$bread=(isset($_POST['bread']))?$_POST['bread']:chr(0);
?>

Posted: Mon Feb 10, 2003 2:48 pm
by volka
it's not an error, it's a notice/a warning. The script tries to (read-)access a variable that is not defined/set. If the user does not fill in the field 'bread' there will be no $_POST['bread'] and that's what the notice tries to tell you. It will not stop the script, it's only a notice that shall make you aware of this.
You can test the existance e.g. with isset($_POST['bread'])

Posted: Mon Feb 10, 2003 6:36 pm
by Winter
Thank you so much... you solve my problem...

Winter :lol: