php - How can I insert only values in text boxes where corresponding check boxes are checked? -
in program, have 4 checkboxes correspond 4 text fields. php script should insert values database checkboxes checked. unfortunately, works if all of checkboxes checked. why this?
here testchk.html
<html> <head> <title>testchk</title> </head> <body bgcolor="pink"> <h3> choice item</h3> <form action="testchk.php" method="post"> <input type="checkbox" name="chk1[]" value="vegetables">vegetables <input type="text" name="temperature[]"><br /> <input type="checkbox" name="chk1[]" value="frozen">frozen products <input type="text" name="temperature[]"><br /> <input type="checkbox" name="chk1[]" value="dried">dried goods <input type="text" name="temperature[]"><br /> <input type="checkbox" name="chk1[]" value="cooling"> <input type="text" name="temperature[]"><br /> <br> <input type="submit" name="submit" value="submit"> </form> </body> </html>
and here testchk.php
include ("db.php"); $checkbox1 = $_post['chk1']; $temperature = $_post['temperature']; if ($_post["submit"]=="submit") { ($i=0; $i<sizeof($checkbox1); $i++) { $sql="insert test (name, temp) values ('".$checkbox1[$i]."', '".$temperature[$i]."' )"; mysql_query($sql) or die(mysql_error()); } echo "insert"; }
this because of difference between how checkboxes , text inputs handled. checkboxes have checked submitted form, of text inputs submitted whether have entered them or not. when name inputs using []
, php generate numeric indices arrays. means if not check checkboxes, index numbers checkboxes not match index numbers text inputs. can fix explicitly defining index numbers in html:
<input type="checkbox" name="chk1[0]" value="vegetables">vegetables <input type="text" name="temperature[0]"><br> <input type="checkbox" name="chk1[1]" value="frozen">frozen products <input type="text" name="temperature[1]"><br> <input type="checkbox" name="chk1[2]" value="dried">dried goods <input type="text" name="temperature[2]"><br> <input type="checkbox" name="chk1[3]" value="cooling"> <input type="text" name="temperature[3]"><br>
then can use foreach instead deal ones checkbox checked.
foreach($checkbox1 $index => $column_name) { // query using $temperature[$index]; }
Comments
Post a Comment