melaniecarr23 Posted September 25, 2011 Share Posted September 25, 2011 Here is the issue: I am creating an input form which would allow someone to check multiple boxes. These checkboxes are populated from a table called reasonforcare. Here is my code: <?php $rows = mysql_num_rows($reasonforcare); for ($i=0; $i < $rows; ++$i) { $row = mysql_fetch_row($reasonforcare); echo "<input name='reasonforcare' type='checkbox' value='" . $row[0] . "'/>"; echo $row[1]; } ?> I get all the checkboxes to show up, but at the end of the last database entry there is an extra checkbox! Can someone help me figure out why this is happening? Quote Link to comment https://forums.phpfreaks.com/topic/247811-dynamic-checkboxes-extra-checkbox/ Share on other sites More sharing options...
melaniecarr23 Posted September 25, 2011 Author Share Posted September 25, 2011 This is frustrating as can be! I've taken way too much time off and have to totally relearn everything! When I view source on the page, here is what I'm getting: <td><input name='reasonforcare[]' type='checkbox' value='2'/>Problems breast feeding<input name='reasonforcare[]' type='checkbox' value='3'/>Failure to thrive<input name='reasonforcare[]' type='checkbox' value='4'/>Congenital torticollis<input name='reasonforcare[]' type='checkbox' value='5'/>Otitis media/externa<input name='reasonforcare[]' type='checkbox' value='6'/>Infantile scoliosis<input name='reasonforcare[]' type='checkbox' value='7'/>Bronchitis tonsilitis<input name='reasonforcare[]' type='checkbox' value='8'/>Restless sleep<input name='reasonforcare[]' type='checkbox' value='9'/>Disturbed motor responses with repetitive falls<input name='reasonforcare[]' type='checkbox' value='10'/>Balance and coordination problems<input name='reasonforcare[]' type='checkbox' value='11'/>Prolonged infant reflexes<input name='reasonforcare[]' type='checkbox' value='12'/>ADHD<input name='reasonforcare[]' type='checkbox' value='13'/>Autism<input name='reasonforcare[]' type='checkbox' value='14'/>Weakened immune system<input name='reasonforcare[]' type='checkbox' value='15'/>Head ache<input name='reasonforcare[]' type='checkbox' value='16'/>Neck pain<input name='reasonforcare[]' type='checkbox' value='17'/>Low back pain<input name='reasonforcare[]' type='checkbox' value=''/> </td> I can't figure out what the heck I'm doing wrong!!! I want the items to be listed and have the value="" start at 1, and it keeps starting at 2! I also want to be able to add whatever checkboxes are checked to the table historyconditions as a separate row, but all I got was one entry in that table. I know I need to make it an array, but ARGH!!!! Quote Link to comment https://forums.phpfreaks.com/topic/247811-dynamic-checkboxes-extra-checkbox/#findComment-1272518 Share on other sites More sharing options...
jcbones Posted September 25, 2011 Share Posted September 25, 2011 Because array's start at 0, and num_rows start at 1. So you will have to subtract 1 from num_rows in order to get the highest index from the array. <?php $array[] = 1; $array[] = 2; $count = count($array); echo $count; echo '<pre>' . print_r($array,true) . '</pre>'; ?> I used count, but it functions similar to num_rows. Quote Link to comment https://forums.phpfreaks.com/topic/247811-dynamic-checkboxes-extra-checkbox/#findComment-1272519 Share on other sites More sharing options...
jcbones Posted September 25, 2011 Share Posted September 25, 2011 I suppose $row[0] is the primary key (id) and $row[1] is the name. <?php if(mysql_num_rows($reasonforcare) > 0) { while($row = mysql_fetch_row($reasonforcare)) { echo "<input name='reasonforcare' type='checkbox' value='{$row[0]}'/> {$row[1]} \n"; } } Make sure there are no other lines like these BEFORE the code above. <?php $row = mysql_fetch_assoc($reasonforcare); //or $row = mysql_fetch_array($reasonforcare); //or $row = mysql_fetch_row($reasonforcare); If any of these exist before the code provided, then the array pointer will increment to the next index. It will look as if one of the rows isn't being retrieved from the database. Quote Link to comment https://forums.phpfreaks.com/topic/247811-dynamic-checkboxes-extra-checkbox/#findComment-1272520 Share on other sites More sharing options...
PFMaBiSmAd Posted September 25, 2011 Share Posted September 25, 2011 I'm going to guess in your actual full code, somewhere between the msyql_query() statement and the code you did post, that you have a mysql_fetch_xxxxx statement that is fetching and discarding the first row in the result set. Quote Link to comment https://forums.phpfreaks.com/topic/247811-dynamic-checkboxes-extra-checkbox/#findComment-1272522 Share on other sites More sharing options...
melaniecarr23 Posted September 25, 2011 Author Share Posted September 25, 2011 Thanks everyone for the help. Is there a trick to getting the page to insert a new row into the table for each checkbox checked? Cause so far, I've only been able to get it to insert one of the checked items. Quote Link to comment https://forums.phpfreaks.com/topic/247811-dynamic-checkboxes-extra-checkbox/#findComment-1272653 Share on other sites More sharing options...
jcbones Posted September 25, 2011 Share Posted September 25, 2011 <?php foreach($_POST['reasonforcare'] as $value) { $sql[] = "('{$value}')"; } $query = "INSERT INTO table (columnName) VALUES " . implode(' , ', $sql); I could help you more if I knew what kind of data we are talking about. ie table names, column names, table relations, etc. Quote Link to comment https://forums.phpfreaks.com/topic/247811-dynamic-checkboxes-extra-checkbox/#findComment-1272661 Share on other sites More sharing options...
melaniecarr23 Posted September 25, 2011 Author Share Posted September 25, 2011 Here is my insert code: if ((isSET($_POST["MM_insert"])) && ["MM_insert"] = "form1")) { $insertSQL = sprintf("INSERT INTO historyconditions (historyconditionID, patientID, categoryID, conditionID) VALUES (%s, %s, %s, %s)", GetSQLValueString($_POST['historyconditionID'], "int"), GetSQLValueString($_POST['patientID], "text"), GetSQLValueString($_POST['categoryID'], "int"), GetSQLValueString($_POST['reasonforcare'], "int")); Are you saying I should nest this into the foreach code below, so it will insert a new record and change the value of 'reasonforcare'? Quote Link to comment https://forums.phpfreaks.com/topic/247811-dynamic-checkboxes-extra-checkbox/#findComment-1272678 Share on other sites More sharing options...
Pikachu2000 Posted September 25, 2011 Share Posted September 25, 2011 Are you sure that's the actual code? That should never insert anything, as it has parse errors. Paste the actual code if you want help. Quote Link to comment https://forums.phpfreaks.com/topic/247811-dynamic-checkboxes-extra-checkbox/#findComment-1272685 Share on other sites More sharing options...
melaniecarr23 Posted September 25, 2011 Author Share Posted September 25, 2011 Ok, here is the code for the entire page so far. I get the correct number of records inserted, but the conditionID is zero for all of them, instead of the value of that checkbox. <?php require_once('Connections/hordb.php'); ?> <?php function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") { $theValue = (!get_magic_quotes_gpc()) ? addslashes($theValue) : $theValue; switch ($theType) { case "text": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "long": case "int": $theValue = ($theValue != "") ? intval($theValue) : "NULL"; break; case "double": $theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL"; break; case "date": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "defined": $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue; break; } return $theValue; } $editFormAction = $_SERVER['PHP_SELF']; if (isset($_SERVER['QUERY_STRING'])) { $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']); } if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) { foreach($_POST['reasonforcare'] as $value) { $sql[] = "('{$value}')"; $insertSQL = sprintf("INSERT INTO historyconditions (historyconditionID, patientID, categoryID, conditionID) VALUES (%s, %s, %s, %s)", GetSQLValueString($_POST['historyconditionID'], "int"), GetSQLValueString($_POST['patientID'], "text"), GetSQLValueString($_POST['categoryID'], "int"), GetSQLValueString('$sql[]', "int")); mysql_select_db($database_hordb, $hordb); $Result1 = mysql_query($insertSQL, $hordb) or die(mysql_error()); }} mysql_select_db($database_hordb, $hordb); $query_historycategories = "SELECT * FROM historycategory ORDER BY historycategoryID ASC"; $historycategories = mysql_query($query_historycategories, $hordb) or die(mysql_error()); $row_historycategories = mysql_fetch_assoc($historycategories); $totalRows_historycategories = mysql_num_rows($historycategories); mysql_select_db($database_hordb, $hordb); $query_reasonforcare = "SELECT * FROM reasonforcare ORDER BY reasonforcareID ASC"; $reasonforcare = mysql_query($query_reasonforcare, $hordb) or die(mysql_error()); $totalRows_reasonforcare = mysql_num_rows($reasonforcare); $colname_patientID = "-1"; if (isset($_GET['recordID'])) { $colname_patientID = (get_magic_quotes_gpc()) ? $_GET['recordID'] : addslashes($_GET['recordID']); } mysql_select_db($database_hordb, $hordb); $query_patientID = sprintf("SELECT subjectID FROM demographics WHERE subjectID = '%s'", $colname_patientID); $patientID = mysql_query($query_patientID, $hordb) or die(mysql_error()); $row_patientID = mysql_fetch_assoc($patientID); $totalRows_patientID = mysql_num_rows($patientID); ?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Untitled Document</title> <link href="CSS/Accessible_Design.css" rel="stylesheet" type="text/css" /> </head> <body> <p> </p> <form method="post" name="form1" action="<?php echo $editFormAction; ?>"> <table align="center"> <tr valign="baseline"> <td nowrap align="right">PatientID:</td> <td><input type="text" name="patientID" value="<?php echo $row_patientID['subjectID']; ?>" size="32"> <input name="categoryID" type="hidden" value="1" /></td> </tr> <tr valign="baseline"> <td nowrap align="right">Reason for Care :</td> <td><?php if (mysql_num_rows($reasonforcare) > 0) { while($row = mysql_fetch_row($reasonforcare)) { echo "<input name='reasonforcare[]' type='checkbox' value='{$row[0]}'/> {$row[1]} \n"; } } ?> </td> </tr> <tr valign="baseline"> <td nowrap align="right"> </td> <td><input type="submit" value="Insert record"></td> </tr> </table> <input type="hidden" name="historyconditionID" value=""> <input type="hidden" name="categoryID" value="1"> <input type="hidden" name="MM_insert" value="form1"> </form> <p> </p> </body> </html> <?php mysql_free_result($historycategories); mysql_free_result($reasonforcare); mysql_free_result($patientID); ?> Quote Link to comment https://forums.phpfreaks.com/topic/247811-dynamic-checkboxes-extra-checkbox/#findComment-1272691 Share on other sites More sharing options...
Pikachu2000 Posted September 25, 2011 Share Posted September 25, 2011 The value is assigned to an array element in the foreach() loop, and the array is not reinitialized, so on each iteration of the loop, the array index (which starts at zero) is incremented. The value will not be in $sql[], it will be in sql[0], $sql[1], etc. The good news is that this is easy to remedy. Since there's no need to even use an array, just change the foreach() loop to assign the value to $sql instead of $sql[], and do the same in the sprintf() for the query string. That's all I see right off the bat, so give that a try and see how it goes. Quote Link to comment https://forums.phpfreaks.com/topic/247811-dynamic-checkboxes-extra-checkbox/#findComment-1272698 Share on other sites More sharing options...
melaniecarr23 Posted September 25, 2011 Author Share Posted September 25, 2011 Thanks. I kind of understand what you are saying, but not really. I did change the two instances of $sql[] to $sql, but the results are still being input into the database with a conditionID of 0 for each checkbox checked, rather than the value assigned to the checkboxes (1-17 accordingly). What am I doing wrong? Arrays confuse the crap out of me. Quote Link to comment https://forums.phpfreaks.com/topic/247811-dynamic-checkboxes-extra-checkbox/#findComment-1272710 Share on other sites More sharing options...
melaniecarr23 Posted September 25, 2011 Author Share Posted September 25, 2011 I GOT IT!!!! I needed to change the following code: $sql[] = "('{$value}')"; to this: $sql = "$value" By using echo $sql; I was able to see the values were showing up as ('1') ('2') etc. instead of 1 2 3. Thanks so much for all your help!!! That was driving me crazy! Quote Link to comment https://forums.phpfreaks.com/topic/247811-dynamic-checkboxes-extra-checkbox/#findComment-1272714 Share on other sites More sharing options...
jcbones Posted September 26, 2011 Share Posted September 26, 2011 If it were me, I would re-write the whole insert block of code as shown above. 1. I do not advocate running queries in loops. This is unneeded overhead, and stress on the mysql server. 2. It can be more efficient since you only need to clean the variables ONCE. <?php if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) { $historyID = GetSQLValueString($_POST['historyconditionID'],'int'); $patientID = GetSQLValueString($_POST['patientID'],'text'); $categoryID = GetSQLValueString($_POST['categoryID'],'int'); foreach($_POST['reasonforcare'] as $value) { $value = (int)$value; $sql[] = "('{$historyID}','{$patientID}','{$categoryID}','{$value}')"; } $insertSQL = "INSERT INTO historyconditions (historyconditionID, patientID, categoryID, conditionID) VALUES " . implode(' , ',$sql); mysql_select_db($database_hordb, $hordb); mysql_query($insertSQL, $hordb) or die(mysql_error()); echo mysql_affected_rows() . ' rows has been inserted into the database!'; } Quote Link to comment https://forums.phpfreaks.com/topic/247811-dynamic-checkboxes-extra-checkbox/#findComment-1272736 Share on other sites More sharing options...
melaniecarr23 Posted September 26, 2011 Author Share Posted September 26, 2011 I see what you mean. Thanks! Quote Link to comment https://forums.phpfreaks.com/topic/247811-dynamic-checkboxes-extra-checkbox/#findComment-1272752 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.