PHP - Looking For A Better Way To Handle Check Boxes
Hi guys
On the edit profile page on my website, im trying to get is so that when the user first opens the page, if the database field reads "1" the checkbox is checked. However if the user unchecks it and makes a mistake on the form which returns an error, the checkbox remains unchecked. Also if the user unchecks the text box, the 1 in the database is changed to a 0. And vise versa. The only way i have got it to work succesfully is by using the following: <?php $test = $_POST['test']; $submit = $_POST['submit']; if (!isset($test)) { $test="0"; } else { $test="1"; } if ($submit) { mysql_query("UPDATE profiles SET test='$test' WHERE username='user'"); echo "ok"; } ?> <html> <form action="test.php" method="POST"> <input type="checkbox" name="test" <?php if ($submit) { if ($test=="1") { echo "checked='checked'";}} else { if ($row['test'] == "1") {echo "checked='checked'";}} ?> /> <input type="submit" name="submit" /> </form> </html> My problem is, i have about 60 check boxes on the page, and i dont really want to write the code below for all of them: if (!isset($test)) { $test="0"; } else { $test="1"; } Does anybody know a better way to do this so i dont end up with 420 lines of extra code? Many thanks. Similar TutorialsHello there, I'm new to this site/forum so i dont know if this is the right forum to post a code review / commentary request .... I have a function that handels the sql code... Know i would like to know what you think off it ? can I do something different or better ?.. Code: [Select] <?PHP /* * Private function db_query($sql) | handle.... * whit checking en extendid error reporting.... * Runs a query but does not return a result array.... * @String $sql | this is the sql query you whant to run..... */ private function db_query($sql) { $this->sql = $sql; switch ( DEBUG_QUERY ) { // check debug mode... case true: try { // probeer query uit te voeren... $handle = $this->query($this->sql); if(!$handle) // if error whit the query... { $this->rollback(); throw new Exception('MySQLi Query went wrong error ==> ' . mysqli::$error); } } catch (Exception $e) { // error afhandeling and reporting.. echo '<hr />'; echo '<span style="color:red"><b>A MySQLi Query went wrong:</b></span><br />'; echo var_dump($e->getMessage()); echo '<br />'; echo nl2br($e->getTraceAsString()); echo '<br />'; echo 'Error in File: ' . $e->getFile(); echo '<br />'; echo 'Thrown Exception on line: ' . $e->getLine(); echo '<br /><hr />'; exit(); } // end error afhandeling and reporting... break; case false: $handle = $this->query($this->sql); break; } // end switch... return $handle; } /* * Public function db_Do | handels the insert, update, select and delete query's * A lot off optional options for the different query's * @String $type | Choose between the four type's | select, insert, update or delete | Default is Select * @String $table | Select witch table you whant to use | give a vailid tablename you whant to use in the query * @String $values | Input the values uw whant to select from the table | * for all - row1, row2, row3 | id, username, password * @String $where | The where operator for the query | Where $where = | give a vailid row name | if used you must fill in the other two where operators | default = empty (optional) * @String $opparator | The operator for the where operator | =, >, <, <>, >=, <=, !=, ==, ===, !==, LIKE, IS, IS NOT, +, -, /, %, * | whit check in_array | where 2 | default = empty (optional) * @String / Int $where_val | The where value for the where operator | WHERE $where{id} $opparator{=} $where_val{1} | where 3 | default = empty (optional) * @Bool $use_and | if TRUE you can use the AND operator | linked to the other three and operators | if you use 1 you must fill in all 4 of them | default = false (optional) * @String $and_key | Value for the AND operator | same as $order_by | AND $and_key{username} | and 2 | default = empty (optional) * @String $and_oparetor | The operator for the and section | same as $opparator | =, >, <, <>, >=, <=, !=, ==, ===, !==, LIKE, IS, IS NOT, +, -, /, %, * | whit check in_array | and 3 | default = '=' (optional) * @String $and_value | The value for by the and_key | same as $where_val | AND $and_key{username} $and_oparetor{=} $and_value{'jhon'} | and 4 | default = empty (optional) * @String $order_by | value for the Order by operator only used if hase a value | ORDER BY $order_by{id} | if used you must alsow fill in the second order by operator | default = empty (optional) * @String $order_key | Value for the Order key by the order value | ORDER BY $order_by{id} $order_key{asc, desc} | check in_array | default = asc (optional) * Error msg and checks includid, Failsafe... * Runs the query and returns a row.... * Uses the db_query function... * Version 1.0.0 */ public function db_Do($type = 'select', $table, $values, $where = NULL, $opparator = NULL, $where_val = NULL, $use_and = FALSE, $and_key = NULL, $and_oparetor = '=', $and_value = NULL, $order_by = NULL, $order_key = 'ASC') { switch ( DEBUG_QUERY ) { // check debug mode... case true: if(in_array($type, $this->SQL_TYPE, TRUE)) { // check for correct $type... if(in_array($order_key, $this->ORDER_KEY, TRUE)) { // check if order key is allowd $order_key.... if(in_array($opparator, $this->OPARATORS, TRUE)) { // check for vallid oparetors... if(empty($table) or strlen($table) >= 4) { // check if $table correct is.... if(empty($values) or strlen($values) >= 4) { // check if the $values are given correctly.... if(in_array($and_oparetor, $this->OPARATORS, TRUE)) { // check if and oparetor is allowd..... switch( $type ) { // witch type... case 'select': // Build the SQL Query.... $query = 'SELECT '. $this->real_escape_string($values) .' FROM '. $table .' '; if(!empty($where) and (empty($where_val) or empty($opparator))) { $row = 'Sorry you have to fill in all 3 of the where conditions!'; return $row; } elseif(!empty($where) || !empty($where_val) || !empty($opparator)) { $query .= 'WHERE '. $where .' '. $opparator .' "'. $this->real_escape_string($where_val) .'" '; } if($use_and == true and !empty($and_key) and !empty($and_value)) { $query .= 'AND '. $and_key .' '. $and_oparetor .' "'. $this->real_escape_string($and_value) .'" '; } elseif($use_and == true and (empty($and_key) or empty($and_value))) { $row = 'Sorry you have to fill in all 3 off the AND oparetors correctly.'; return $row; } if(!empty($order_by)) { $query .= ' ORDER BY '. $order_by .' '. $order_key .''; } $this->sql = $query; $handle = $this->db_query($this->sql); $row = $handle->fetch_assoc(); mysqli_free_result($handle); break; case 'insert': // Build the SQL Query...... $query = 'INSERT INTO '. $table .' ('. $this->real_escape_string($values) .') '; $query .= 'VALUES ('. $this->real_escape_string($where) .')'; $this->sql = $query; $handle = $this->db_query($this->sql); $row = ($handle) ? true : false; unset($handle); // empty / unset $handle... break; case 'update': // Build the SQL Query...... $query = 'UPDATE '. $table .' '; $query .= 'SET '. $this->real_escape_string($values) .' '; if(!empty($where) and !empty($where_val) and !empty($opparator)) { $query .= 'WHERE '. $where .' '. $opparator .' "'. $this->real_escape_string($where_val) .'" '; } elseif(empty($where) or empty($where_val) or empty($opparator)) { $row = 'Sorry you have to fill in all 3 of the where conditions!'; return $row; } if($use_and == true and !empty($and_key) and !empty($and_value)) { $query .= 'AND '. $and_key .' '. $and_oparetor .' "'. $this->real_escape_string($and_value) .'" '; } elseif($use_and == true and (empty($and_key) or empty($and_value))) { $row = 'Sorry you have to fill in all 3 off the AND oparetors correctly.'; return $row; } $this->sql = $query; $handle = $this->db_query($this->sql); $row = ($handle) ? true : false; unset($handle); // empty / unset $handle.... break; case 'delete': //Construct the delete query..... $query = 'DELETE FROM '. $table .' '; $query .= 'WHERE '. $where .' '. $opparator .' "'. $this->real_escape_string($where_val) .'" '; if($use_and == true and !empty($and_key) and !empty($and_value)) { $query .= 'AND '. $and_key .' '. $and_oparetor .' "'. $this->real_escape_string($and_value) .'" '; } elseif($use_and == true and (empty($and_key) or empty($and_value))) { $row = 'Sorry you have to fill in all 3 off the AND oparetors correctly.'; return $row; } $this->sql = $query; $handle = $this->db_query($this->sql); $row = ($handle) ? true : false; unset($handle); // empty / unset $handle.... break; } // end switch( $type )..... } else { // Correct Oparetors...... $row = 'Incorrect Oparetor in the AND section choose out: =, >, <, <>, >=, <=, !=, ==, ===, !==, LIKE, IS, IS NOT, +, -, /, %, * or use the FreeQuery'; } } else { // Correct VALUES..... $row = 'Sorry you have to fill in the values parameter correctly and it hase to be bigger then 3 chars.'; } } else { // Correct TABLE.... $row = 'Sorry you have to fill in the table parameter correctly and it hase to be bigger than 3 chars.'; } } else { // Correct Oparetors...... $row = 'Incorrect Oparetor in the WHERE section choose out: =, >, <, <>, >=, <=, !=, ==, ===, !==, LIKE, IS, IS NOT, +, -, /, %, * or use the FreeQuery'; } } else { // if order_key is NOT allowd.... $row = 'Incorrect Order by opparator: <b>'. $order_key .'</b> choos between (asc or desc)'; } } else { // if not correct type return error msg.... $row = 'Incorrect type: <b>'. $type . '</b> choose between (select, insert, update or delete)'; } break; // end case true... case false: break; // end case false... } // end switch( debug_query )... return $row; } // end public function db_Do()..... ?> It's still a work in process so it's not done yet... Hi, im new to php and got a simple query. i have built a web gallery and i want to add keywords to pictures, ive built the interface and mysql statements so it lists all possible keywords and creates a tick box for the user to use. ive created a table to join the image id's to my keyword id's as its going to be a many to many relationship, ive also built the sql statement below to select the highlighted image, but im not sure how i can join the looping of all keywords to generate the tick boxes and then to loop again to populate the tickboxes that are saved within the DB - if that makes sense?? SELECT * FROM images,img_key,keywords where img_key.img_id=images.id and keywords.id=img_key.key_id and images.id='2' I was using this wonderful tutorial on dynamic check boxes and databases http://www.phpfreaks.com/tutorial/working-with-checkboxes-and-a-database . This example is uses checkboxes to give users admin rites. I have tried to revamp this code to handle more inputs from checkboxes but some where I have made some errors. <?php include("db.php"); $updated = FALSE; if(count($_POST) > 0){ $DEP = $_POST['MMARS_DEP']; array_map('intval',$DEP); $DEP = implode(',',$DEP); mysql_query("UPDATE master_roles SET MMARS_DEPT=0") or trigger_error(mysql_error(),E_USER_ERROR); mysql_query("UPDATE master_roles SET MMARS_DEPT=1 WHERE id IN ($DEP)") or trigger_error(mysql_error(),E_USER_ERROR); $MD = $_POST['MMARS_MD']; array_map('intval',$MD); $MD = implode(',',$MD); mysql_query("UPDATE master_roles SET MMARS_MD=0") or trigger_error(mysql_error(),E_USER_ERROR); mysql_query("UPDATE master_roles SET MMARS_MD=1 WHERE id IN ($MD)") or trigger_error(mysql_error(),E_USER_ERROR); $ORG = $_POST['MMARS_ORG']; array_map('intval',$ORG); $ORG = implode(',',$ORG); mysql_query("UPDATE master_roles SET MMARS_ORG=0") or trigger_error(mysql_error(),E_USER_ERROR); mysql_query("UPDATE master_roles SET MMARS_ORG=1 WHERE id IN ($ORG)") or trigger_error(mysql_error(),E_USER_ERROR); $SEC = $_POST['MMARS_SEC']; array_map('intval',$SEC); $SEC = implode(',',$SEC); mysql_query("UPDATE master_roles SET MMARS_SEC=0") or trigger_error(mysql_error(),E_USER_ERROR); mysql_query("UPDATE master_roles SET MMARS_SEC=1 WHERE id IN ($SEC)") or trigger_error(mysql_error(),E_USER_ERROR); $BOG = $_POST['MMARS_BOG']; array_map('intval',$BOG); $BOG = implode(',',$BOG); mysql_query("UPDATE master_roles SET MMARS_BOG=0") or trigger_error(mysql_error(),E_USER_ERROR); mysql_query("UPDATE master_roles SET MMARS_BOG=1 WHERE id IN ($BOG)") or trigger_error(mysql_error(),E_USER_ERROR); $SW = $_POST['MMARS_SW']; array_map('intval',$SW); $SW = implode(',',$SW); mysql_query("UPDATE master_roles SET MMARS_SW=0") or trigger_error(mysql_error(),E_USER_ERROR); mysql_query("UPDATE master_roles SET MMARS_SW=1 WHERE id IN ($SW)") or trigger_error(mysql_error(),E_USER_ERROR); $updated=TRUE; } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>phpfreaks checkbox tutorial</title> </head> <body> <form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post"> <?php if($updated===TRUE){ echo '<div>Privileges Updated!</div>'; } ?> <table> <tr> <th><td>DEPT</td><td>MD</td><td>ORG</td><td>SEC</td><td>BOG</td><td>SW</td></th> <?php $label = array('MMARS','LCM','NM SEC','Classic MMARS','CAPS','PMIS','WRK COMP'); $table = array('MMars','LCM', 'NMSec', 'ClassMars', 'CAPS', 'PMIS', 'WrkComp'); $i= 0; while($i < 1){ echo "<tr>" ."<td>".$label[$i]."</td>"; $array = array(); $count = 0; $Aid = mysql_query("SELECT DISTINCT id FROM DB") or die (mysql_error()); while ($row= mysql_fetch_assoc($Aid)){ $ID = $row['id']."<br>"; $array[$count] = $ID; $count++; } $Disabled =""; $sql = "SELECT id, UAID, DB_NAME, MMARS_DEPT, MMARS_MD, MMARS_ORG, MMARS_SEC, MMARS_BOG, MMARS_SW FROM master_roles WHERE `UAID`='1000' AND id <= 6"; $result = mysql_query($sql) or trigger_error(mysql_error(),E_USER_ERROR); $row = mysql_fetch_row($result); list($id, $UAID, $DB_NAME, $MMARS_DEP, $MMARS_MD, $MMARS_ORG, $MMARS_SEC, $MMARS_BOG, $MMARS_SW)= $row; $checked = ($MMARS_DEPT==1) ? 'checked="checked"' : ''; echo '<td>'.$array[0].'<input type="checkbox" name="MMARS_DEP[]" value="'.$array[0].'" '.$checked.' , '.$Disabled.' /></td>'; $checked = ($MMARS_MD==1) ? 'checked="checked"' : ''; echo '<td>'.$array[1].'<input type="checkbox" name="MMARS_MD[]" value="'.$array[1].'" '.$checked.' , '.$Disabled.' /></td>'; $checked = ($MMARS_ORG==1) ? 'checked="checked"' : ''; echo '<td>'.$array[2].'<input type="checkbox" name="MMARS_ORG[]" value="'.$array[2].'" '.$checked.' , '.$Disabled.' /></td>'; $checked = ($MMARS_SEC==1) ? 'checked="checked"' : ''; echo '<td>'.$array[3].'<input type="checkbox" name="MMARS_SEC[]" value="'.$array[3].'" '.$checked.' , '.$Disabled.' /></td>'; $checked = ($MMARS_BOG==1) ? 'checked="checked"' : ''; echo '<td>'.$array[4].'<input type="checkbox" name="MMARS_BOG[]" value="'.$array[4].'" '.$checked.' , '.$Disabled.' /></td>'; $checked = ($MMARS_SW==1) ? 'checked="checked"' : ''; echo '<td>'.$array[5].'<input type="checkbox" name="MMARS_SW[]" value="'.$array[5].'" '.$checked.', '.$Disabled.' /></td>'; echo "</tr>"; $i ++; } ?> <tr><td colspan="2"><input type="submit" name="submit" value="Update Privileges" /></td></tr> </table> </form> </body> </html> After the post each individual checkbox input is saved into a variable then we query the database and check if any of the checkboxes have been changed to 1. If so then than right is updated to one. if(count($_POST) > 0){ $DEP = $_POST['MMARS_DEP']; array_map('intval',$DEP); $DEP = implode(',',$DEP); mysql_query("UPDATE master_roles SET MMARS_DEPT=0") or trigger_error(mysql_error(),E_USER_ERROR); mysql_query("UPDATE master_roles SET MMARS_DEPT=1 WHERE id IN ($DEP)") or trigger_error(mysql_error(),E_USER_ERROR); $MD = $_POST['MMARS_MD']; array_map('intval',$MD); $MD = implode(',',$MD); mysql_query("UPDATE master_roles SET MMARS_MD=0") or trigger_error(mysql_error(),E_USER_ERROR); mysql_query("UPDATE master_roles SET MMARS_MD=1 WHERE id IN ($MD)") or trigger_error(mysql_error(),E_USER_ERROR); $ORG = $_POST['MMARS_ORG']; array_map('intval',$ORG); $ORG = implode(',',$ORG); mysql_query("UPDATE master_roles SET MMARS_ORG=0") or trigger_error(mysql_error(),E_USER_ERROR); mysql_query("UPDATE master_roles SET MMARS_ORG=1 WHERE id IN ($ORG)") or trigger_error(mysql_error(),E_USER_ERROR); $SEC = $_POST['MMARS_SEC']; array_map('intval',$SEC); $SEC = implode(',',$SEC); mysql_query("UPDATE master_roles SET MMARS_SEC=0") or trigger_error(mysql_error(),E_USER_ERROR); mysql_query("UPDATE master_roles SET MMARS_SEC=1 WHERE id IN ($SEC)") or trigger_error(mysql_error(),E_USER_ERROR); $BOG = $_POST['MMARS_BOG']; array_map('intval',$BOG); $BOG = implode(',',$BOG); mysql_query("UPDATE master_roles SET MMARS_BOG=0") or trigger_error(mysql_error(),E_USER_ERROR); mysql_query("UPDATE master_roles SET MMARS_BOG=1 WHERE id IN ($BOG)") or trigger_error(mysql_error(),E_USER_ERROR); $SW = $_POST['MMARS_SW']; array_map('intval',$SW); $SW = implode(',',$SW); mysql_query("UPDATE master_roles SET MMARS_SW=0") or trigger_error(mysql_error(),E_USER_ERROR); mysql_query("UPDATE master_roles SET MMARS_SW=1 WHERE id IN ($SW)") or trigger_error(mysql_error(),E_USER_ERROR); The html is a straight forward form. I have arrays set up and while loop ready for implementation because I plan on having this repeat multiple times. ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>phpfreaks checkbox tutorial</title> </head> <body> <form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post"> <?php if($updated===TRUE){ echo '<div>Privileges Updated!</div>'; } ?> <table> <tr> <th><td>DEPT</td><td>MD</td><td>ORG</td><td>SEC</td><td>BOG</td><td>SW</td></th> <?php $label = array('MMARS','LCM','NM SEC','Classic MMARS','CAPS','PMIS','WRK COMP'); $table = array('MMars','LCM', 'NMSec', 'ClassMars', 'CAPS', 'PMIS', 'WrkComp'); $i= 0; while($i < 1){ echo "<tr>" ."<td>".$label[$i]."</td>"; I had a lot of problems keeping the id unique for each checkbox. This is why I created an array with the ids and I use them as "value" in the input field. $array = array(); $count = 0; $Aid = mysql_query("SELECT DISTINCT id FROM DB") or die (mysql_error()); while ($row= mysql_fetch_assoc($Aid)){ $ID = $row['id']."<br>"; $array[$count] = $ID; $count++; } I sql the database for id, UAID, DB_NAME, and all of the necessary rites. With list I assign each row with the correct name. Each checkbox's associated field in the db is checked to see if it is set to 1. If it is checked="checked". $sql = "SELECT id, UAID, DB_NAME, MMARS_DEPT, MMARS_MD, MMARS_ORG, MMARS_SEC, MMARS_BOG, MMARS_SW FROM master_roles WHERE `UAID`='1000' AND id <= 6"; $result = mysql_query($sql) or trigger_error(mysql_error(),E_USER_ERROR); $row = mysql_fetch_row($result); list($id, $UAID, $DB_NAME, $MMARS_DEPT, $MMARS_MD, $MMARS_ORG, $MMARS_SEC, $MMARS_BOG, $MMARS_SW)= $row; $checked = ($MMARS_DEPT==1) ? 'checked="checked"' : ''; echo '<td>'.$array[0].'<input type="checkbox" name="MMARS_DEP[]" value="'.$array[0].'" '.$checked.' , '.$Disabled.' /></td>'; $checked = ($MMARS_MD==1) ? 'checked="checked"' : ''; echo '<td>'.$array[1].'<input type="checkbox" name="MMARS_MD[]" value="'.$array[1].'" '.$checked.' , '.$Disabled.' /></td>'; $checked = ($MMARS_ORG==1) ? 'checked="checked"' : ''; echo '<td>'.$array[2].'<input type="checkbox" name="MMARS_ORG[]" value="'.$array[2].'" '.$checked.' , '.$Disabled.' /></td>'; $checked = ($MMARS_SEC==1) ? 'checked="checked"' : ''; echo '<td>'.$array[3].'<input type="checkbox" name="MMARS_SEC[]" value="'.$array[3].'" '.$checked.' , '.$Disabled.' /></td>'; $checked = ($MMARS_BOG==1) ? 'checked="checked"' : ''; echo '<td>'.$array[4].'<input type="checkbox" name="MMARS_BOG[]" value="'.$array[4].'" '.$checked.' , '.$Disabled.' /></td>'; $checked = ($MMARS_SW==1) ? 'checked="checked"' : ''; echo '<td>'.$array[5].'<input type="checkbox" name="MMARS_SW[]" value="'.$array[5].'" '.$checked.', '.$Disabled.' /></td>'; I am attaching a print out of my joined table I am querying as well as my final vision for this form. In advance, thank you for your help. I cannot figure out why my checkbox values are not being included in my emails I am posting my html and my php.
<form method="post" action="../leaf.php"> <input type="hidden" name="subject" value="Cleanup"> <div> <table width="425" border="0" cellspacing="0" cellpadding="0"> <tr> <td><label><span class="ie7bugfix01">Name:<span class="colour">*<br /> </span></span> <input type="text" name="contact-name" class="text" value="" /></label></td> <td><label><span class="ie7bugfix01">Email:<span class="colour">*</span></span><br /> <input type="text" name="contact-email" class="text" value="" /></label></td> </tr> <tr> <td> <label><span class="ie7bugfix01">Phone No:</span> <br /> <input type="text" name="contact-mobile" class="text" value="" /></label> </td> </tr> <tr> <td><label><span class="ie7bugfix01">Address:<br /> </span> <input type="text" name="contact-street" class="text" value="" /></label></td> <td><label><span class="ie7bugfix01">City:</span><br /> <input type="text" name="contact-city" class="text" value="" /></label></td> </tr> <tr> <td><label><span class="ie7bugfix01">Property Size:<br /> </span> <input type="text" name="property-size" class="text" value="" /></label></td> </tr> <tr> <td><label><span class="ie7bugfix01">Service request:</span><br /></label> <input type="checkbox" name="projects[]" value="Lawn Maintenance"> <label for="type1">Lawn Maintenance</label> <br> <input type="checkbox" name="projects[]" value="Mulching"> <label for="type2">Mulching</label> <br> <input type="checkbox" name="projects[]" value="Gutter Cleaning/Repair"> <label for="type3">Gutter Cleaning/Repair</label> <br> <input type="checkbox" name="projects[]" value="Revitalization"> <label for="type1">Revitalization</label> <br> <input type="checkbox" name="projects[]" value="Power Washing"> <label for="type2">Power Washing</label> <br> </td><td> <br> <input type="checkbox" name="projects[]" value="Hardscapes"> <label for="type3">Hardscape</label> <br> <input type="checkbox" name="projects[]" value="Deck Work"> <label for="type3">Deck Treatments/Repair/Construction</label> <br> <input type="checkbox" name="projects[]" value="Snow Removal"> <label for="type3">Snow Removal</label> <br><input type="checkbox" name="projects[]" value="Tree Trimming"> <label for="type3">Tree Trimming/Removal</label> <br> <input type="checkbox" name="projects[]" value="Privacy Barriers"> <label for="type3">Privacy Barriers</label> </td></tr> <tr> </tr> </table> <label><span class="ie7bugfix01">Describe your project:<span class="colour">*</span></span><br /> <textarea name="contact-comments" class="text" cols="68" rows="5"></textarea></label> <p class="submit"> <input type="submit" class="submit" value="submit" /> <input type="button" class="reset" value="reset" /> </p> </div></form> <?php $from = $_REQUEST['contact-email'] ; $name = $_REQUEST['contact-name'] ; $subject = $_REQUEST['subject'] ; $headers = "From: $from"; $headers = "Subject: $subject"; $fields = array(); $fields{"subject"} = "Subject"; $fields{"contact-name"} = "Name"; $fields{"contact-email"} = "E-mail"; $fields{"contact-mobile"} = "Phone"; $fields{"contact-street"} = "Address"; $fields{"contact-city"} = "City"; $fields{"property-size"} = "Size"; $selectedProjects = 'None'; if(isset($_POST['projects']) && is_array($_POST['projects']) && count($_POST['projects']) > 0){ $selectedProjects = implode(', ', $_POST['projects']); } $body .= 'Selected Projects: ' . $selectedProjects; $fields{"contact-comments"} = "Message"; $body = "We have received the following information:\n\n"; foreach($fields as $a => $b){ $body .= sprintf("%20s: %s\n",$b,$_REQUEST[$a]); } $headers2 = "From: t***@toma***.com"; $subject2 = "Thank you for contacting us"; $autoreply = "Thank you for contacting us. Somebody will get back to you as soon as possible, usualy within 48 hours. By choosing TOMA you will be able to enjoy your time off with the peace of mind that your lawn is always professionally serviced. Never worry about finding time to work in the lawn again and gain back at least 35 hours of summer this season! TOMA provides weekly as needed lawn maintenance for your home or business. We are dedicated to every detail of your unique lawn. We always arrive with sharp blades, we police your property and we make sure everything is left freshly groomed and clean. Easy to sign up, easy billing, invest in your home and time today! FREE ESTIMATES WHEN YOU CALL ________. If you have any more questions, please consult our website at www.t**.com or call _________ to get started."; if($from == '') {print "You have not entered an email, please go back and try again";} else { if($name == '') {print "You have not entered a name, please go back and try again";} else { $send = mail("t***@t**.com", $subject, $body, $headers); $send2 = mail($from, $subject2, $autoreply, $headers2); if($send) {header( "Location: http://www.**t.com/thank-you.html" );} else {print "We encountered an error sending your mail, please try again"; } } } ?> Is it possible to have multiple check boxes on a single form and a single submit button tp post the values into different rows of DB Kenny I have a set of 26 checkboxes that are stored in an array. The below code dumps the comma separated array values into a single record column. Code: [Select] // dumping the type of job checkboxes $type = $_POST['type']; var_dump($type); // Setting up a blank variable to be used in the coming loop. $allStyles = ""; // For every checkbox value sent to the form. foreach ($type as $style) { // Append the string with the current array element, and then add a comma and a space at the end. $allTypes .= $style . ", "; } // Delete the last two characters from the string. $allTypes = substr($allTypes, 0, -2); // end dumping the type of job checkboxes This works great! But my needs go past this. The record can be edited. So I need to get the values back out of the database and populate the correct check boxes for editing. The checkboxes are generated by this code. Code: [Select] <div class="text">Job Type (<a class="editlist" href="javascript:editlist('listedit.php?edit=typelist',700,400);">edit list</a>):</div> <div class="field"> <?PHP $connection=mysql_connect ("localhost", "name", "pass") or die ("I cannot connect to the database."); $db=mysql_select_db ("database", $connection) or die (mysql_error()); $query = "SELECT type FROM typelist ORDER BY type ASC"; $sql_result = mysql_query($query, $connection) or die (mysql_error()); $i=1; echo '<table valign="top"><tr><td>'; while ($row = mysql_fetch_array($sql_result)) { $type = $row["type"]; if ($i > 1 && $i % 26 == 0) echo '</td><td>'; else if ($i) echo ''; ++$i; echo "<input style='font-size:10px;' name='type[]' type='checkbox' value='$type'><span style='color:#000;'>$type</span></input><br/>"; } echo '</td></tr></table>'; ?> </div> I am having a problem getting these checkboxes repopulated. I think that a way to do this is to: Get the values out of the database in a array Compare the values the list of all possible values. Check the boxes of the values confirmed to be there. I didn't build the application so I need help to work through this problem. Hey guy, I have a form where I want to validate if the check boxes have been checked or not and store that in a session. If a box is not selected I want an error message to echo. With what I've done so far, if a box is selected the form works but if one is not selected my error message does not show and I get an undefined Index Notice. Can anyone tell me where I'm going wrong. Page 1- form <form action="processPage7.php" method="post"> <br /> <p>Check the times you are most likely to have available:</p> <input type="checkbox" name="days[]" value="Evenings" <?php if(isset($_POST['days']) == 'Evenings') echo 'checked' ?>> Weekday evenings<br /> <input type="checkbox" name="days[]" value="Weekdays" <?php if(isset($_POST['days']) == 'Weekdays') echo 'checked' ?>> Week Days<br /> <input type="checkbox" name="days[]" value="Weekends" <?php if(isset($_POST['days']) == 'Weekends') echo 'checked' ?>> Weekend Days<br /> </div><br /><br /> <p><input type="submit" value="Next Page" /></p><input type="reset" value="Reset" /> </form> Page 2- <?php session_start(); if($_SERVER['REQUEST_METHOD']== 'POST'){ $valid_form = TRUE; // NO PROBLEMS if(!isset($_POST['days'])){ echo "Error, no time selected. Please go back and select a time."; }else{ $_SESSION['days'] = $_POST['days']; } if($valid_form == TRUE){ header('Location: FormProcess.php'); } } ?> And Page 3 <?php session_start(); $days = $_SESSION['days']; $chkResults = $days; for ($i = 0;$i<=count($chkResults)-1;$i++){ echo "<p>". $days[$i]; } ?> Thanks in advance. im developing a voting system where you can vote for multiple choices using checkboxes.. upon submitting the vote form, votecounts must automatically be updated.. values for votecount will come from the checkbox value 1. ive been having a hard time trying to figure out hot to update multiple rows with checkbox values..any help would be appreciated..thanks in advance! here's the code: Code: [Select] $editFormAction = $_SERVER['PHP_SELF']; if (isset($_SERVER['QUERY_STRING'])) { $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']); } if ((isset($_POST["MM_update"])) && ($_POST["MM_update"] == "form_vote")) $i=1;{ while ($i<= $totalRows_rs_candi) { $updateSQL = "UPDATE tbl_candidates SET votecount={$_POST['votecount']} WHERE user_id={$_POST['candi']}"; mysql_select_db($database_organizazone_db, $organizazone_db); $Result1 = mysql_query($updateSQL, $organizazone_db) or die(mysql_error()); $i++; } if (isset($_SERVER['QUERY_STRING'])) { $updateGoTo = "vote_success.php"; } header(sprintf("Location: %s", $updateGoTo)); } Code: [Select] <form id="form_vote" name="form_vote" method="POST" action="<?php echo $editFormAction; ?>"> <table border="1"> <tr> <td> </td> <td>user_id</td> <td>l_name</td> <td>course_id</td> <td>yearlevel</td> <td>about</td> </tr> <?php $i=1; do { ?> <tr> <td><span id="sprycheckbox1"> <input name="votecount[<?php echo $i ?>]" type="checkbox" id="votecount" value="1" /> <span class="checkboxMinSelectionsMsg">Minimum number of selections not met.</span></span> <label for="votecount[]"></label></td> <td><label for="candi"></label> <input name="candi" type="text" disabled="disabled" id="candi" value="<?php echo $row_rs_candi['user_id']; ?>" readonly="readonly" /></td> <td><?php echo $row_rs_candi['l_name'].' ,'.$row_rs_candi['f_name'].' '.$row_rs_candi['m_name']; ?></td> <td><?php echo $row_rs_candi['course_id']; ?></td> <td><?php echo $row_rs_candi['yearlevel']; ?></td> <td><?php echo $row_rs_candi['about_me']; ?></td> </tr> <?php $i++; ?> <?php } while ($row_rs_candi = mysql_fetch_assoc($rs_candi)); ?> </table> I really need some huge help on deleting rows with check boxes. Im completly lost on how to do this. Read some examples online and even with the code being small to do this i cant figure it out on intergrading it with the code I wrote. sorry that the code is long on this. I have decent comments though. At the very bottom i have started writing the delete code. My problem is figuring out how to make the script know what check box is checked. I have a select all check box java script on this page too Code: [Select] <form name="frm1" id="frm1" action="" method="post" 15.onsubmit="javascript:return submitIt('frm1')"> <p> <center> <table width="60%" border="1" cellspacing="1" cellpadding="0"> <tr align="center"> </tr> <tr align="center"> <td><input type="checkbox" name="checkAll" value="x" id="checkall" onclick="checkUncheckAll('association[]', this.checked)" /></td> <td>Recipient</td> <td>Subject</td> <td>Sent</td> <td>read/unread</td> </tr> <?php // find out how many rows are in the table $count3 = "SELECT COUNT(*) FROM sent WHERE id = '".($_SESSION['user_id'])."'";; $count2 = mysql_query($count3) or trigger_error("SQL", E_USER_ERROR); $r = mysql_fetch_row($count2); $numrows = $r[0]; // number of rows to show per page $rowsperpage = 10; // find out total pages $totalpages = ceil($numrows / $rowsperpage); // get the current page or set a default if (isset($_GET['sent']) && is_numeric($_GET['sent'])) { // cast var as int $currentpage = (int) $_GET['sent']; } else { // default page num $currentpage = 1; }// end if // if current page is greater than total pages... if ($currentpage > $totalpages) { // set current page to last page $currentpage = $totalpages; }// end if // if current page is less than first page... if ($currentpage < 1) { // set current page to first page $currentpage = 1; } // end if // the offset of the list, based on current page $offset = ($currentpage - 1) * $rowsperpage; // get the info from the db $count3 = "SELECT * FROM sent WHERE id = '".($_SESSION['user_id'])."' ORDER BY time DESC LIMIT $offset, $rowsperpage "; $count2 = mysql_query($count3) or trigger_error("SQL", E_USER_ERROR); // while there are rows to be fetched... while ($list = mysql_fetch_assoc($count2)) { // these are variables to place in the echo $sent_id = $list['sent_id']; $recipient = $list['sendto']; $subject = $list['subject']; $read = $list['read']; // grabs the time offset $take3 = "SELECT time_offset FROM users WHERE id='".mysql_real_escape_string($_SESSION['user_id'])."'"; $take2 = mysql_query($take3) or die(mysql_error()); $take1 = mysql_fetch_array($take2); $recieved = $list['time']; // adds the users time offset to the inputed time $time = ($recieved + $take1['time_offset']); // sets default time to UTC then formats the inputed time that was offset with the users offset date_default_timezone_set('UTC'); $user_offset = date('h:i:s a M/d', $time); ?> <tr> <td><center><input type="checkbox" name="association[]" id="<?php echo $sent_id; ?>" value="1" /></center></td> </label></td> <td><center><a href="search_goaulds.php?goauld=<?php echo $recipient; ?>"><?php echo $recipient ?></a></center></td> <td><center><a href="sent_view.php?sent_id=<?php echo $sent_id; ?>"><?php echo $subject ?></a></center></td> <td><center><?php echo $read ?></center></td> <td><center><?php echo $user_offset ?></center></td> </tr> <?php } // while loop ?> </table> </center> <div class="deletecontainer"> <div class="delete"> <br/> <input type="submit" name="delete" id="delete" value="Delete"></p> </form> </div> </div> <?php if(isset($_POST['delete'])) { // if checkbox is checked with the matching sent_id if(isset($_POST['sent_id'])) { // then delete sent_id matching the checkbox id mysql_query("DELETE FROM `sent` WHERE `sent_id`= '".($_POST['sent_id'])."'"); } } ?> Hi Everyone, I am having problems when submitting a form that has check boxes within it (post.php). All the check boxes have a name and a checked value of 1 - the receiving page (for example submit.php) has the variables defined: $tickbox1 = $_POST['tickbox1']; The problem I am finding is that if the box isnt checked - I get an "index is not defined" error. I would suppose because there is no value. I have tried this before and it has worked, however that was on Apache and this is on IIS. Is there a work around? Thanks Matt I have a list of checkboxes, like e.g each checkbox has a value as ResumeID, now question is/are; 1) how to get the values of the checkboxes using jQuery ? 2) when I got the values of the checkboxes using jQuery, how to pass those values to a PHP Controller action ? Hi There! I am quite far with this script I'm creating, but there is one thing I am not getting straight. The script shows and hides information from a database by changing checkboxes. This can be filtered by a form. Now my final problem: the checkboxes should start CHECKED instead of unchecked as they start now. It could be done by giving the $film or the $a attribute a start value I guess, but I don't know how. I tried to put $a = "checked=\"checked\""; $film_query = "film='1'"; on several places in the beginning of the script, but it doesn't seem to affect anything. It only works if I put it right before the form, but then it checks the checkboxes every time after the form has been submitted (making it impossible to uncheck it). Not good Could you give me a little help maybe? Thanks a LOT! I am new to PHP and learning as I go I am stuck with a piece of code that I am trying to change. I have a php application that has tickboxes in and some are checked as standard. I want to change the tick box setting to be unchecked as standard. Here is the code. <label><input type="checkbox" name="notify" value="1" <?php echo (!isset($_SESSION['as_notify']) || !empty($_SESSION['as_notify'])) ? 'checked="checked"' : ''; ?> /> <?php echo $hesklang['seno']; ?></label><br /> I have tried everything I know but since I do not know that much I have been unable to change the standard. I am sure it is something small that I am overlooking. Anyone out there know what I am doing wrong? Hey! I have it so users can submit info to my site. They have to check some check boxes and radio buttons. I want them to be able to edit this information, so I want to have the data pulled from the MySQL database and have the correct radio button selected (and the text bolded). So I'm thinking some sort of array to check for each value in the database... but I don't really know. There are a few groups of radio boxes and check boxes but here is an example of one. Code: [Select] <input type="radio" name="stage" value="Stage 1" /> Stage 1 <input type="radio" name="stage" value="Stage 2" /> Stage 2 <input type="radio" name="stage" value="Stage 3" /> Stage 3 The information is pulled from the database like this: Code: [Select] $res=mysql_query("SELECT * FROM ACTIVE WHERE INDEX_ID=$id"); if(mysql_num_rows($res)==0) echo "There is no data in the table <br /> <br />"; else { for($i=0;$i<mysql_num_rows($res);$i++) { $row=mysql_fetch_assoc($res); } } So when I pull information (lets say I want to echo it) it'd look like this: Code: [Select] $row[STAGE] The value for the stage selection can only be Stage 1, Stage 2 or Stage 3 so I need it to be selected when the page loads. Thanks! I have a form that has a section where you can pick multiple check boxes and when the info is returned to me it has the word Array at the end of it. There are 2 check boxes on the form one fo Steve and one for Ben Below is the code I am using in my PHP file foreach($_POST['TestGroup'] as $val) { echo $val . "\n"; } The output from the PHP code is----Steve Ben Array.------ How do I keep Array from coming up? I am attempting to submit a form that includes multiple check boxes for one data field. I have set it up the implode the data and make it a comma delimited array. I am able to echo the results, yet I have not been able to post the information to the database. I believe that I have just one simple thig to do, yet I am not being successful. Here is my code I have attached the .txt file also: <?php require_once('Connections/rotarysantarosa.php'); ?> <?php if (isset($_POST['submit'])) { if (isset($_POST['currentClubPosition'])) { $strcurrentClubPosition = implode(",", $_POST['currentClubPosition']); } else { $strcurrentClubPosition = ""; } } ?> <?php if (!function_exists("GetSQLValueString")) { function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") { if (PHP_VERSION < 6) { $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue; } $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($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"] == "frmMemberInsert")) { $insertSQL = sprintf("INSERT INTO members (firstName, lastName, photo, pastPresident, currentClubPosition, classification, workPosition, company, workAddress, workCity, workState, workZip, officePhone, fax, homePhone, cellPhone, email, website, homeAddress, homeCity, homeState, homeZip, birthdayMonth, birthdayDay, spouse, yearJoined) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)", GetSQLValueString($_POST['firstName'], "text"), GetSQLValueString($_POST['lastName'], "text"), GetSQLValueString($_POST['photo'], "text"), GetSQLValueString($_POST['pastPresident'], "text"), GetSQLValueString($_POST['currentClubPosition'], "text"), GetSQLValueString($_POST['classification'], "text"), GetSQLValueString($_POST['workPosition'], "text"), GetSQLValueString($_POST['company'], "text"), GetSQLValueString($_POST['workAddress'], "text"), GetSQLValueString($_POST['workCity'], "text"), GetSQLValueString($_POST['workState'], "text"), GetSQLValueString($_POST['workZip'], "text"), GetSQLValueString($_POST['officePhone'], "text"), GetSQLValueString($_POST['fax'], "text"), GetSQLValueString($_POST['homePhone'], "text"), GetSQLValueString($_POST['cellPhone'], "text"), GetSQLValueString($_POST['email'], "text"), GetSQLValueString($_POST['website'], "text"), GetSQLValueString($_POST['homeAddress'], "text"), GetSQLValueString($_POST['homeCity'], "text"), GetSQLValueString($_POST['homeState'], "text"), GetSQLValueString($_POST['homeZip'], "text"), GetSQLValueString($_POST['birthdayMonth'], "text"), GetSQLValueString($_POST['birthdayDay'], "int"), GetSQLValueString($_POST['spouse'], "text"), GetSQLValueString($_POST['yearJoined'], "int")); mysql_select_db($database_rotarysantarosa, $rotarysantarosa); $Result1 = mysql_query($insertSQL, $rotarysantarosa) or die(mysql_error()); $insertGoTo = "members.php"; if (isset($_SERVER['QUERY_STRING'])) { $insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?"; $insertGoTo .= $_SERVER['QUERY_STRING']; } header(sprintf("Location: %s", $insertGoTo)); } mysql_select_db($database_rotarysantarosa, $rotarysantarosa); $query_rsStates = "SELECT * FROM states ORDER BY stateName ASC"; $rsStates = mysql_query($query_rsStates, $rotarysantarosa) or die(mysql_error()); $row_rsStates = mysql_fetch_assoc($rsStates); $totalRows_rsStates = mysql_num_rows($rsStates); mysql_select_db($database_rotarysantarosa, $rotarysantarosa); $query_rsMemberInsert = "SELECT * FROM members ORDER BY lastName ASC"; $rsMemberInsert = mysql_query($query_rsMemberInsert, $rotarysantarosa) or die(mysql_error()); $row_rsMemberInsert = mysql_fetch_assoc($rsMemberInsert); $totalRows_rsMemberInsert = mysql_num_rows($rsMemberInsert); mysql_select_db($database_rotarysantarosa, $rotarysantarosa); $query_rsClubPosition = "SELECT * FROM clubpositions ORDER BY `Club Position` ASC"; $rsClubPosition = mysql_query($query_rsClubPosition, $rotarysantarosa) or die(mysql_error()); $row_rsClubPosition = mysql_fetch_assoc($rsClubPosition); $totalRows_rsClubPosition = mysql_num_rows($rsClubPosition); mysql_select_db($database_rotarysantarosa, $rotarysantarosa); $query_rsClassification = "SELECT * FROM classifications ORDER BY Classification ASC"; $rsClassification = mysql_query($query_rsClassification, $rotarysantarosa) or die(mysql_error()); $row_rsClassification = mysql_fetch_assoc($rsClassification); $totalRows_rsClassification = mysql_num_rows($rsClassification); mysql_select_db($database_rotarysantarosa, $rotarysantarosa); $query_rsBirthMonth = "SELECT * FROM birthdaymonth"; $rsBirthMonth = mysql_query($query_rsBirthMonth, $rotarysantarosa) or die(mysql_error()); $row_rsBirthMonth = mysql_fetch_assoc($rsBirthMonth); $totalRows_rsBirthMonth = mysql_num_rows($rsBirthMonth); mysql_select_db($database_rotarysantarosa, $rotarysantarosa); $query_rsBirthDay = "SELECT * FROM birthdayday ORDER BY birthdayday ASC"; $rsBirthDay = mysql_query($query_rsBirthDay, $rotarysantarosa) or die(mysql_error()); $row_rsBirthDay = mysql_fetch_assoc($rsBirthDay); $totalRows_rsBirthDay = mysql_num_rows($rsBirthDay); ?> Hello All: Trying to work with PHP on a contact form with a jQuery Validation to make certain that the visitors fill out the required information. I'll try to show everything that I have, and then the error I am getting when the visitor hits "submit." I don't know PHP all that well, and trying to learn my way through it. I used a couple of tutorials to add the features I needed and did my own styling on the live site. Here is the PHP that is currently in the header of my markup: <?php //If the form is submitted if(isset($_POST['submit'])) { //Check to make sure that the First name field is not empty if(trim($_POST['firstname']) == '') { $hasError = true; } else { $firstname = trim($_POST['firstname']); } //Check to make sure that the Last name field is not empty if(trim($_POST['lastname']) == '') { $hasError = true; } else { $lastname = trim($_POST['lastname']); } //Check to make sure that the Street Address 01 field is not empty if(trim($_POST['street01']) == '') { $hasError = true; } else { $street01 = trim($_POST['street01']); } //If Street02 is filled out, give it a value $street02 = $_POST['street02']; //Check to make sure that the City field is not empty if(trim($_POST['city']) == '') { $hasError = true; } else { $city = trim($_POST['city']); } //Check to make sure that the State field is not empty if(trim($_POST['state']) == '') { $hasError = true; } else { $state = trim($_POST['state']); } //Check to make sure that the Zip field is not empty if(trim($_POST['zip']) == '') { $hasError = true; } else { $zip = trim($_POST['zip']); } //If Email is filled out, give it a value $email = $_POST['email']; //If Telephone is filled out, give it a value $telephone = $_POST['telephone']; //Default Subject Value $subject = "VMC Inquiry"; //Check checkboxes foreach($_POST['check'] as $value) { $check_msg = "Checked: $value\n"; } //If Message is filled out, give it a value $comment = $_POST['comment']; //If there is no error, send the email if(!isset($hasError)) { $emailTo = 'xxxx.xxxx@gmail.com'; //Put your own email address here $body = "Name: $firstname $lastname \n\nStreet Address: $street01 \n\nStreet Address*: $street02 \n\nCity: $city \n\nState: $state \n\nZip: $zip \n\nEmail*: $email \n\nTelephone*: $telephone \n\nCheck Box: $check_msg \n\nMessage:\n $comment"; $headers = 'From: XXXXX <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email; mail($emailTo, $subject, $body, $headers); $emailSent = true; } } ?> So basically I am using classes to say whether or not something is required, which ties into the jQuery validation. If it isn't required, whatever the visitor types into the box is put into something like "$telephone" which is then printed in the e-mail. The markup for the forms in the body is the following: Code: [Select] <p class="contact-text-right">For more information, or to have a list of our properties mailed to you, please fill out the form below.</p> <div id="contact-wrapper"> <?php if(isset($hasError)) { //If errors are found ?> <p class="error">Please check if you've filled all the fields with valid information. Thank you.</p> <?php } ?> <?php if(isset($emailSent) && $emailSent == true) { //If email is sent ?> <p class="accept"><strong><?php echo $firstname;?>,Your Email Successfully Sent!</strong></p> <?php } ?> <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" id="contactform"> <div id="names"> <label for="firstname"><strong>First Name:</strong></label> <input type="text" name="firstname" id="firstname" value="" class="required" /> <label for="lastname"><strong>Last Name:</strong></label> <input type="text" name="lastname" id="lastname" value="" class="required" /> </div> <div id="address01"> <label for="street01"><strong>Street Address:</strong></label> <input type="text" name="street01" id="street01" value="" class="required" /> </div> <div id="address02"> <label for="street02"><strong>Street Address*:</strong></label> <input type="text" name="street02" id="street02" value="" /> </div> <div id="city"> <label for="city"><strong>City:</strong></label> <input type="text" name="city" id="city" value="" class="required city" /> <label for="state"><strong>State:</strong></label> <input type="text" name="state" id="state" value="" class="required state" /> <label for="zip"><strong>Zip Code:</strong></label> <input type="text" name="zip" id="zip" value="" class="required zip" /> </div> <div id="email"> <label for="email"><strong>E-mail*:</strong></label> <input type="text" name="email" id="email" value="" class="email"/> <label for="telephone"><strong>Telephone*:</strong></label> <input type="text" name="telephone" id="telephone" value="" class="telephone" /> <p class="bottom">*Optional fields.</p> </div> <div class="checkbox"> <p><input type="checkbox" name="check[]" value="properties">XXX</p> <p><input type="checkbox" name="check[]" value="contact-regarding">XXXX</p> <p class="indent">(Please list properties or ask specific questions in the space below.)</p> </div> <div id="comment"> <label for="comment"></label> <textarea name="comment" id="comment" ></textarea> </div> <div id="button"> <input type="submit" value="Send Message" name="submit" /> </div> </form> All seems well until I hit submit on the live site. I think get this error returned to me: Warning: Invalid argument supplied for foreach() in ......./html/development/contact.php on line 64 The e-mail goes through, with all the information, no problems! I just can't get this error message to go away. Line 64 of contact.php is where the checkbox coding is: //Check checkboxes foreach($_POST['check'] as $value) { $check_msg = "Checked: $value\n"; } I know I've submitted a lot of code here, and tried to narrow you down to the exact spot I think the problem is, but hopefully some of you PHP gurus can pick out the flaw in a heartbeat. I really appreciate all the help. B I've been trying to simplify this code, let alone make it work. It's a loop to change the different question checkboxes to "checked" if certain degree_ids are found. All of the examples i have looked at are very strange and I'm not sure how to go about this, thought it seems to be a common question. Everyone seems to have their own way. Any advice would be greatly appreciated. for($i =1; $i <= $arraycount; $i++){ $query = "SELECT degree_id FROM `user-degree` WHERE `user_id` = '".$user_id."' AND degree_id = '".$i."'"; $result = $conn->query($query) or die(mysql_error()); $row = mysqli_fetch_array($result) ; echo $row['degree_id']; if(!$y){ $y = 0; } if ($row['degree_id'] == 1){ $q4[0] = 'checked'; } if ($row['degree_id'] == 2){ $q4[1] = 'checked'; } if ($row['degree_id'] == 3){ $q4[2] = 'checked'; } if ($row['degree_id'] == 4){ $q4[3] = 'checked'; } if ($row['degree_id'] == 5){ $q4[4] = 'checked'; } if ($row['degree_id'] == 6){ $q4[5] = 'checked'; } if ($row['degree_id'] == 7){ $q4[6] = 'checked'; } if ($row['degree_id'] == 8){ $q4[7] = 'checked'; } if ($row['degree_id'] == 9){ $q4[8] = 'checked'; } } So I'm sitting at my desk scratching my head on how to do a task where I pull information form a database (that i know how to do) but then i need to see if two variables equal a string and if they do count out how many times that two variables equal there two string checks and out put the counted number ? this is what I have thought of but dose not to work because I cant figure out a way to code it? $dbPull = mysql_fetch_array($result) if( $dbPull['Foo'] == 'string1' && $bdPull['Bar'] == 'string2') this is were I get lost I'm looking for (how many times in the DB dose String2 show up in the array were the above, IF statement is true ) any ideas would be most appreciated So i got a table that looks somthing like this: File Name | Download | Suggested Catagory | Select Catagory | Approve -------------------------------------------------------------------------------------- test | Download | blah blah blah | Option menu | yes or no option menu test | Download | blah blah blah | Option menu | yes or no option menu test | Download | blah blah blah | Option menu | yes or no option menu what I want to do is in the file that processes this it only looks at the ones that have had the "approve column" submitted as a yes. Next it will to a mysql entry into verrified notes. Problem is with X amount of entries in that form I dont know how to look at only the ones that have said yes. Do I create a new form for each entry or put them all as one entry and after this what do I do next? |