PHP - Dynamic Checkboxes - Extra Checkbox
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: Quote <?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? Similar TutorialsHi all, I need some help here. Currently I am using 2 functions. 1) To call out the 'academic levels' 2) To call out the 'subjects' which matches to the specific 'academic level' However, I am stucked in the codes. Please view my picture attachment, my question is, how do I assigned 'red box (Pre-School)' to 'red box (subjects)' and so on...What are the codes or tweaks that I should make so that it will look like 'what do I want to achieve.jpg' My process and execution $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) or die(mysqli_error($dbc)); //Run query $tutor_id = mysqli_real_escape_string($dbc, $_GET['tutor_id']); $query = "SELECT tl.level_id, tl.level_name, ts.subject_id, ts.subject_name, tsl.subject_level_id, IF(tosl.tutor_id='{$tutor_id}', 1, 0) as checked FROM tutor_level AS tl INNER JOIN tutor_subject_level AS tsl USING (level_id) INNER JOIN tutor_subject AS ts USING (subject_id) LEFT JOIN tutor_overall_level_subject AS tosl ON tosl.subject_level_id = tsl.subject_level_id AND tosl.tutor_id = '{$tutor_id}' ORDER BY tl.level_id, ts.subject_name"; $sql = mysqli_query($dbc, $query) or die(mysqli_error($dbc)); $query1 = "SELECT tl.level_id, tl.level_name, IF(tslvl.tutor_id='{$tutor_id}', 1, 0) as checked FROM tutor_level AS tl LEFT JOIN tutor_selected_level AS tslvl ON tslvl.level_id = tl.level_id AND tslvl.tutor_id='{$tutor_id}' ORDER BY tl.level_id, tl.level_name"; $sql1 = mysqli_query($dbc, $query1) or die(mysqli_error($dbc)); //Process the results $checkboxes = ''; //Create variable for output $current_level_id = false; //Flag to check when records change level while($data = mysqli_fetch_array($sql)) //Iterate throug the DB results { if($current_level_id != $data['level_id']) //Determine if this level is different from the last { print_r ($data); $subjectCheckboxes .= createSubjectCheckboxes($subject_data, 5); $current_level_id = $data['level_id']; $subject_data = array(); } //Add the current record to the $level_data array $subject_data[] = $data; } //$checkboxes .= createLevelCheckboxes($subject_data, $level_data, 5); while($data1 = mysqli_fetch_array($sql1)) { print_r ($data1); $levelCheckboxes .= createLevelCheckboxes($level_data, 5); $level_data = array(); $level_data[] = $data1; } //Call the createLevelCheckboxes() function to generate the HTML for the LAST level records $levelCheckboxes .= createLevelCheckboxes($level_data, 5); $subjectCheckboxes .= createSubjectCheckboxes($subject_data, 5); My functions function createLevelCheckboxes($levelArray, $columns) { if(count($levelArray)==0) { return false; } $htmlOutput = ''; foreach($levelArray as $data1) { //Display level header row $levelID = $levelArray[0]['level_id']; $levelName = $levelArray[0]['level_name']; $checked = ($data1['checked'] == 1) ? ' checked="checked"' : ''; $htmlOutput .= "<tr>\n"; $htmlOutput .= "<th colspan=\"{$columns}\" style=\"text-align:left;padding-top:15px;\">"; $htmlOutput .= "<input name=\"level[]\" type=\"checkbox\" id=\"level_{$levelID}\" type=\"checkbox\" {$checked} value=\"{$levelID}\">"; $htmlOutput .= "<span class=\"zone_text_enlarge\"><label for=\"level_{$levelID}\">{$levelName}</label></span>"; $htmlOutput .= "</th>\n"; $htmlOutput .= "</tr>\n"; } return $htmlOutput; } function createSubjectCheckboxes($subjectArray, $columns) { //Display each subject $recordCount = 0; foreach($subjectArray as $data) { //Increment counter $recordCount++; //Start new row if needed, 1/5 = R1 --> So create a new row if ($recordCount % $columns == 1) { $htmlOutput .= "<tr>\n"; } //Display the record $subjectID = $data['subject_level_id']; $subjectName = $data['subject_name']; $checked = ($data['checked'] == 1) ? ' checked="checked"' : ''; $htmlOutput .= " <td>\n"; $htmlOutput .= " <input name=\"subject_level[]\" class=\"subject_a\" type=\"checkbox\" {$checked}"; $htmlOutput .= " id=\"subject_level_{$subjectID}\" value=\"{$subjectID}\"/>\n"; $htmlOutput .= " <label for=\"subject_level_{$subjectID}\" class=\"subject_1\">{$subjectName}</label>\n"; $htmlOutput .= "</td>\n"; //Close row if needed, 5/5 = 0 --> So close the row if ($recordCount % $columns == 0) { $htmlOutput .= "</tr>\n"; } } //Close last row if needed if ($recordCount % $columns != 0) { $htmlOutput .= "</tr>\n"; } return $htmlOutput; } since many do not know the term sticky = when a form is submitted, the data contained is not deleted but instead last checked data will be shown. I have some dynamically generated checkboxes from the database. I tried the below code to make them sticky but they are simply preselected in stead of becoming sticky. What am I doing wrong? <?php $sql2 = "SELECT relation FROM table_rel_info"; $result2 = @mysqli_query($dbc, $sql2); while($row2 = mysqli_fetch_array($result2, MYSQLI_ASSOC)) { echo "<label>" . $row2['relation'] . "</label>"; echo "<input class='box' type='checkbox' value=1"; ?> <?php if (isset($row2['relation'])) { echo 'checked="checked"';}?> <?php echo "'/>" . "<br />"; } ?> Please guys, I need your help on this one. How can call the data from mysql and make the values checked on the checkboxes Have got three tables. I am retrieving data and updating two tables at once... Am new to php... I have been battling on my dynamic checkboxes in such a way that if none is checked the form is return, also I need to retain what was checked when the form postback due to other invalid inputs. Code: [Select] $result = mysql_query("SELECT * FROM course") or die(mysql_error()); if ($result) { while ($row = mysql_fetch_array($result)){ if (isset($_POST['courses']) and $_POST['courses'] == $row['cid']) {echo $row['cid'];} print "<input type=\"checkbox\" name=\"courses[]\" value=\"$row[cid]\">$row[cname]\n"; } } Help needed purely on php codes. Thanks in advance Hello all, I found this dynamic checkbox list online. I have changed it to suit my needs, added some of my own parts but now, after getting past all the terminal errors, it now produces absolutely nothing. Can I get some help on why there is no echo occurring? Thanks! <?php function dynamic_checkbox_table ($sql_str, $col_label, $col_name, $val_checked, $cant_cols_tbl){ $sql_str = dynamic_checkbox_table("SELECT * FROM Categories"); $col_label = "catlevel3"; $col_name = "catlevel3"; $val_checked="S"; $cant_cols_tbl=3; //connect DB and run query $db="TB"; $db_user=""; $pass=""; $host="localhost"; @mysql_connect($host,$db_user,$pass); @mysql_select_db($db) or die ("cannot connect to DB"); $q_resultado = mysql_query($sql_str); mysql_close(); if (mysql_num_rows($q_resultado)==0) exit("no rows returned"); $next_row = mysql_fetch_array($q_resultado); //fetch first row $output = "<table border=\"1\">\n"; //open table tag do { $output .= "<tr>\n"; //open row tag for ($i=1 ; $i <= $cant_cols_tbl ; $i++ ){ //loops as many times as $cant_cols_tbl $row=$next_row; $output .= "<td>"; //open TD tag $output .= (!$row) ? "" : '<input type="checkbox" name="'.$row[$col_name].'" value="'.$val_checked.'" />'.$row[$col_label]; echo (!$row) ? "" : '<input type="checkbox" name="'.$row[$col_name].'" value="'.$row[$val_checked].'" />'.$row[$col_label]; $next_row = mysql_fetch_array($q_resultado); //retrieve next row $output .= "</td>\n"; //close TD } //close for loop $output .= "</tr>\n"; //close row } while ($next_row); //close do-while (and checks if there's another row) $output .= "</table>\n"; //close table return $output; } ?> I got some great help from DavidAM a few days ago that gave me a working function for updating checkboxes when unselected during an editing process later. I was looking for a way to overwrite the old array of values if ALL of the checkboxes were unchecked. The SOLUTION was done with some hard-coding of checkboxes names. I have written a function to find out which checkbox names are going to be called for this form (it can be different multi-value checkboxes loaded depending on the Category of Post the user is trying to make). Now I would like to apply whatever values that come up in a foreach loop after querying the WordPress database to the following function so that instead of hard-coding these three separate multi-value checkboxes I can generate the dynamic code that takes the place of the following: Notice that it needs to know the names of the checkboxes first so I need a looping foreach statement that will takes the results of the query before this that returns an array such as example: (cp_checkbox_help,cp_checkbox_new,cp_checkbox_old,cp_checkbox_stuff) What the query returns in names and the quantity count of these names will vary according to the category id that is passed when the user decides to post into a particular category. if($post_id) { // Make sure the checkbox arrays exist if (! isset($_POST['cp_checkbox_charley'])) $_POST['cp_checkbox_charley'] = array(); if (! isset($_POST['cp_checkbox_help'])) $_POST['cp_checkbox_help'] = array(); if (! isset($_POST['cp_checkbox_hello'])) $_POST['cp_checkbox_hello'] = array(); // now update all the custom fields foreach($_POST as $meta_key => $meta_value) { if (cp_str_starts_with($meta_key, 'cp_')) { if (cp_str_starts_with($meta_key, 'cp_checkbox_charley')) { if (isset($_POST['cp_checkbox_charley'])) $meta_value= implode(',', $_POST['cp_checkbox_charley']); else $meta_value = ''; } if (cp_str_starts_with($meta_key, 'cp_checkbox_help')) { if (isset($_POST['cp_checkbox_help'])) $meta_value = implode(',', $_POST['cp_checkbox_help']); else $meta_value = ''; } if (cp_str_starts_with($meta_key, 'cp_checkbox_hello')) if (isset($_POST['cp_checkbox_hello'])) $meta_value= implode(',', $_POST['cp_checkbox_hello']); else $meta_value = ''; } update_post_meta($post_id, $meta_key, $meta_value); } from a query (I have now built) at this point in the process the script will have returned whatever checkbox names such as cp_checkbox_hello, cp_checkbox_hello, cp_checkbox_charley are relevant to the specific form that is attached to the online Post category a user is trying to Post to. Just what checkbox names are the result of this query will vary according to the Category Id assigned to this Post form. A different category id may bring a different post form to fill out with different multi-value checkboxes names. Which is why this has to be dynamic to take 2 or 3 or 4 or whatever number of names return for checkbox names and then create the following code to handle a variable number of checkboxes that must have the name values filled in. I hope I have explained this clearly enough-- that I want to make the code example dynamic-- right now it takes care of 3 specifically named checkboxes--- I want to get rid of the hardcode and write all of that dynamically, looping through to take care of every situation and every checkbox that may show up. Thank you for taking the time to consider this thoughtfully! Hi, my PHP code currently outputs the results from a users search by querying a backend postgresql database. As result/row is retuned to the user i would like to be able to detect whether or not they have checked a checkbox at the end of each rown in which case multiple rows can then be deleted from the database upon the user clicking a 'delete multiple records' button. I have no problem in being able to display the checkboxes on the webpage but i am a little unsure as to how to refernce them and detect which ones the user has checked. Given my database stores hostnames/IP addresses would it be best to name each checkbox to reflect the hostname or name the value it returns when checked to reflect the hostname. Given the above and that I also store the results of a users search in a $_SESSION['hosts'][][] array how can I then tie the two together? Thanks for reading. Folks, I need help (Php code ) to generate a Dynamic Text on a Base Image. What i want to do is, to make this Image as header on my Site and to make this Header Specific to a Site, i want to Add the Domain Name on the Lower Left of the Image. Got the Idea? Here is the Image link: Quote http://img27.imageshack.us/i/shoppingheader1.jpg/ PHP Variable that holds the Domain name is: $domain All i need the Dynamic PHP Codes that i can put on all my sites to generate this Text on Image (Header) Dynamically... May Anyone Help me with this Please? Cheers Natasha T. Hi all I need to combine these two scripts: Firstly, the following decides which out of the following list is selected based on its value in the mySQL table: <select name="pack_choice"> <option value="Meters / Pack"<?php echo (($result['pack_choice']=="Meters / Pack") ? ' selected="selected"':'') ?>>Meters / Pack (m2)</option> <option value="m3"<?php echo (($result['pack_choice']=="m3") ? ' selected="selected"':'') ?>>Meters / Pack (m3)</option> <option value="Quantity"<?php echo (($result['pack_choice']=="Quantity") ? ' selected="selected"':'') ?>>Quantity</option> </select> Although this works OK, I need it also to show dynamic values like this: select name="category"> <?php $listCategories=mysql_query("SELECT * FROM `product_categories` ORDER BY id ASC"); while($categoryReturned=mysql_fetch_array($listCategories)) { echo "<option value=\"".$categoryReturned['name']."\">".$categoryReturned['name']."</option>"; } ?> </select> I'm not sure if this is possible? Many thanks for your help. Pete I have several lines of text formatted as such: Code: [Select] title text – some more text blah blah blah How do I delete everything after title text from every line ( the and ndash and after)? Thanks! So I'm generating an XML response for Google Maps and this is how my method looks:
/* * Generate XML for google maps * @param results Database results array */ public function generate_xml(array $results) { // Start XML file, create parent node $dom = new DOMDocument("1.0"); $node = $dom->createElement("markers"); $parnode = $dom->appendChild($node); header("Content-type: text/xml"); /* * Iterate through the rows, adding XML nodes for each * Have to do it the ugly way so results aren't pulled twice * (xml and php can't be passed within same array because headers are changed) */ foreach ($results as $row){ $node = $dom->createElement("marker"); $newnode = $parnode->appendChild($node); $newnode->setAttribute('id', $row['id']); $newnode->setAttribute('logo', $row['logo']); $newnode->setAttribute("name", $row['name']); $newnode->setAttribute("address", $row['address']); $newnode->setAttribute('city', $row['city']); $newnode->setAttribute('state', $row['state']); $newnode->setAttribute('zip', $row['zip']); $newnode->setAttribute('phone', $row['phone']); $newnode->setAttribute('email', $row['email']); $newnode->setAttribute('web_link', $row['web_link']); $newnode->setAttribute("lat", $row['lat']); $newnode->setAttribute("lng", $row['lng']); $newnode->setAttribute("distance", $row['distance']); } return $dom->saveXML(); }However, I'm getting this error: This page contains the following errors: error on line 2 at column 1: Extra content at the end of the document for($i=1; $i<=$round; $i++){ print "<tr><td align='left' valign='top'><input type='text' name='number$i' maxlength='2' size='2' /></td>\n "; print "<td align='left' valign='top'><input type='text' name='score$i' maxlength='1' size='1' /></td>\n "; print "<td align='left' valign='top'><select name='team$i'>\n"; print "<option value='-'>-<option>\n"; print "<option value='Home'>Home<option>\n"; print "<option value='Away'>Away<option>\n"; print "</select></td></tr>"; }What I'm having trouble with is that for every option tag there is an empty option tag added. How do I get rid of those empty option tags? Thankful for any help. Hello I was wondering if anyone could help me. I have bought a script that are encoded is something that i cant change or read, and i have ask the owner how to put a {user} at the end of every hyperlink so are going to a other site, but he said you need a external script to do that. So was wondering if anyone could help me. Im using a database where all the user are etc But If i go to google.com and login as Bobmartin I will be at google.com/home Then i click on a hyperlink inside google.com/home that will bring me to a other side Lets say the hyperlink (other site) is www.phpfreaks.com/profile/ So when i begining to redirect to www.phpfreaks.com/profile/ the script will add {user} from the database So at the end i will be redirect to www.phpfreaks.com/profile/Bobmartin The hyperlink is generated in a unique code so i cant just add {user} it must be a external script i need to use. So to say it fast I want to add /{user} for every hyperlink that is redirect to another site without add {user} direct to the hyperlink for example www.google.com/{user}, the hyperlink must me www.google.com Well i hope you guys understand this, im not the best person to explain things so Also my english suck so dont judge me Hi there I followed this post http://www.phpfreaks.com/forums/index.php?topic=95426.0 to get a multi-column layout of search results. All's well but I seem to have an extra blank row at the bottom of the table. This is my code for the table Code: [Select] echo '<table width="800px" class="center" border="1">'; echo '<td>'; if($result && mysql_num_rows($result) > 0) { $i = 0; $max_columns = 3; while ($list = mysql_fetch_array($result)) { // make the variables easy to deal with extract($list); // open row if counter is zero if($i == 0) echo "<tr>"; echo '<td><a href="word.php?w=' . $list['word'] . '">' . $list['word'] . '</a></td>'; // increment counter - if counter = max columns, reset counter and close row if(++$i == $max_columns) { echo "</tr>"; $i=0; } // end if } // end while } // end if results // clean up table - makes your code valid! if($i < $max_columns) { for($j=$i; $j<$max_columns;$j++) echo "<td> </td>"; } echo '</tr>'; echo '</table>'; Any ideas on how not to have it there? Thanks in advance. I have an email form that I use to generate email messages to a club distribution list. I add the body of the message from a form that sends that message to a php script. The emails are a mix of html directly from the script as well as what is sent to the script from the web page form. Example: $mailmessage = '<html><body>header of message' . $MessageFromForm . 'footer of message </body></html>'; **where $MessageFromForm is requested from the form and is the body of the email message. The html header and footer of the message look fine, but the code that came from my html form does not work properly. That code replaces a ' with \', and the html tags do not work. I do have the following included in my headers: $headers = "MIME-Version: 1.0" . "\n"; $headers .= "Content-type:text/html;charset=iso-8859-1" . "\n"; Any ideas on what could cause this? Hello PHPFreaks! I have a question for somebody to answer Code: [Select] <?php //This is the directory where images will be saved $target = "gallery/"; $target = $target . basename( $_FILES['photo']['name']); //This gets all the other information from the form $username=$_POST['username']; $photo=($_FILES['photo']['name']); $caption=$_POST['caption']; $ip=$_POST['ip']; //Writes the information to the database mysql_query("INSERT INTO `photo` (username, photo, caption, ip) VALUES ('$username', '$photo', '$caption', '$ip')") ; //Writes the photo to the server if(move_uploaded_file($_FILES['photo']['tmp_name'], $target)) { //Tells you if its all ok echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded, and your caption has been added to the directory"; } else { //Gives and error if its not echo "Sorry, there was a problem uploading your file."; } ?> When pictures are uploaded; they upload the name they have named them. Is it possible to add to the script $username somewhere to the file name? For example; DSC_0077_SOLAR.JPG Thanks for your time! Hi i've recently moved hosting servers as I had severe lag issues with my shared hosting. Since i've brought a dedicated linux server with apache and php. Since the move i get extra chars with the following code Code: [Select] <?PHP define( "MESSAGE", "Testing Testing 123" ); if(isset($_GET['message'])) { die(MESSAGE); } ?> My application SHOULD receive back "Testing Testing 123" like it used to with my old shared hosting. Instead now it receives the following: Code: [Select] 2f Testing Testing 123 0 And i cannot figure this out for the life of me. I'm expecting something silly to be the cause but would appreciate some guidance on this. Thanks Hey guys I am confused about using checkboxes to delete entries. Yes, just for delete. Codes for table: Code: [Select] echo "<form method = \"post\" action=\"{$_SERVER['PHP_SELF']}\"> <table> <tr> <td width=\"55\" class=\"formLabelsS2\"><input type=\"submit\" name=\"delete\" value=\"Delete\" id=\"delete\"></td> <td> Please note that entries could not be restored once they are deleted!</td> </tr> </table> </form>"; echo "<table class=\"sortable\" id=\"query_quick1\" width=\"100%\" >\r\n"; echo "<thead>"; echo "\t<tr><th></th><th></th><th>Up.dated Query</th><th>Link</th><th>Promoter</th><th> # </th><th>Up?</th> <th>Ana. Area</th><th> # </th><th>Up?</th> <th>C. Type</th><th> # </th><th>Up?</th><th>Other C. Type</th> <th> # </th><th>Up?</th><th>Gen. Back.</th><th> # </th><th>Up?</th> <th>Other Gen. Back.</th><th> # </th><th>Up?</th><th>Author</th><th> # </th><th>Up?</th> <th>Other</th><th> # </th><th>Up?</th><th>Date</th><th>Email</th> <th>F. Name</th><th>L. Name</th></tr>\r\n"; echo "</thead>"; if($result->num_rows){ while ($row = $result->fetch_array()){ $RowCount ++; $row_color = ($RowCount % 2) ? $color1 : $color2; echo "\t<tr class=\"$row_color\" > <form method = \"post\" action=\"{$_SERVER['PHP_SELF']}\"> <td><input type =\"hidden\" name = \"id\" value=\"{$row['id']}\"></td> <td><input name=\"checkbox[]\" type=\"checkbox\" id=\"checkbox[]\" value=\"{$rows['id']} \"></td> <td>{$row['query']}</td><td>{$row['link']}</td> <td>{$row['pro']}</td><td>{$row['pro_count']}</td> <td>{$row['pro_update']}</td> <td>{$row['ana']}</td><td>{$row['ana_count']}</td><td>{$row['ana_update']}</td> <td>{$row['cell']}</td><td>{$row['cell_count']}</td><td>{$row['cell_update']}</td> <td>{$row['cellother']}</td><td>{$row['cellother_count']}</td><td>{$row['cellother_update']}</td> <td>{$row['gen']}</td><td>{$row['gen_count']}</td><td>{$row['gen_update']}</td> <td>{$row['genother']}</td><td>{$row['genother_count']}</td><td>{$row['genother_update']}</td> <td>{$row['author']}</td><td>{$row['author_count']}</td><td>{$row['author_update']}</td> <td>{$row['other']}</td><td>{$row['other_count']}</td><td>{$row['other_update']}</td> <td>{$row['date']}</td><td>{$row['Email']}</td> <td>{$row['First_Name']}</td><td>{$row['Last_Name']}</td> </form></tr>"; } } echo "</table>"; php for deleting entries: Code: [Select] } elseif(isset($_SESSION['user_id']) AND isset($_POST['delete'])){ $connect=db_connect_2(); foreach($_POST['checkbox'] as $check) { $delete = mysqli_query("DELETE FROM mailing_list WHERE id = '$check'"); } $body = "mailingList.php"; } Error pops up: Warning: Invalid argument supplied for foreach() Of course no entries are deleted due to this warning. Help would be greatly appreciated as always Thanks. Okay I am working on a mail script and my only problem is, is that when you select mutiple delete boxes, it only deletes one. How do I get it to delete all of the checked boxes? I am using php to display information from a MySQL database. It starts with three radio buttons and upon selecting one it will display some information for all items in that category. I have all this working but I need to add check boxes for each item and when submitted it will display all information for those items. Below is the bit where I need to insert check box and I'm also attaching my php (leaving out html form and database as it shouldn't be required to help). I must do this as soon as possible, please help. Thanks.. Code: [Select] while ($row = mysql_fetch_assoc ($result_set)) { $ID = $row['id']; $auth = $row['entertainerauthor']; $title = $row['title']; $media = $row['media']; $feature = $row['feature']; printf ("\nID: %s",$ID); printf ("\nEntertainer/Author: %s",$auth); printf ("\nTitle: %s",$title); printf ("\nMedia: %s",$media); printf ("\nFeatu %s",$feature); print "\n"; } |