PHP - Need Help In Building A Dynamic Query To Database For 8 Individual Select Boxes
Hi,
I had a form which contains, 8 select boxes. In those 8 select boxes, 3 of the boxes are interlinked, like, I am able to generate data in other 2 select boxes, if one box is been selected. i.e. based upon selection of one select box, and i am able to generate data in other select box. So, 3 select boxes are interlinked. And remaining 5 selects are optional, if the user selects, then we need to generate data based upon selection of the user. Here the main issue is how to grab data in the post back form, like, how to capture the number of selects boxes selected and what are those selected, and based upon that we need to generate data. Here one more important thing is that, in the report generation form(postback form), I need to show the data in a table. So , in table I had 9 columns and these would be common to whatever the selection made, but, only the requeired data would be changed based upon the selection of the remaining 5 optional boxes. Hope you got me!!!! Similar TutorialsBrand new to the forum, and have only been working with HTML, PHP, & MySQL for about 3 months. I've run into an issue I can't seem to figure out how to work around. I want to have two select boxes, that are dependent on one another. For Example: First box lists types of games: RPG LARP Board Game Miniatures CCG The second box displays game names of the type selected above. I have a MySQL table setup for the second box. To be honest I kinda already have it working... with one small but MAJOR glitch. I select the first box and the page submits using onchange='this.form.submit()'. When the page reloads the first select box reverts back to it's default setting, but the second box does correctly filter & show the content based on the selection that was made in the first box. My Question: How do I set this up so that the first box displays the user selected setting while also passing the $_POST information to the second box? My Code: <table> <tr> <td width=50%> Game Type: </td> <td width=50%> <form name='game_type' action='event_submit.php' method='post'> <select name='game_type' align=center onchange='this.form.submit()' style="width:150px;margin:5px 0 5px 0;"> <option value=''>Chose a Game Type</option> <option value='RPG'>RPG</option> <option value='LARP'>LARP</option> <option value='Board Game'>Board Game</option> <option value='CCG'>Collectable Cards & Games</option> <option value='Miniatures'>Miniatures</option> </select> </form> </td> </tr> <tr> <td width=50%> Game System: </td> <td width=50%> <?php $game_type = $_POST['game_type']; echo "$game_type"; if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("DrowCon", $con); $result = mysql_query("SELECT * FROM Games WHERE Type='$game_type' ORDER BY System ASC"); echo "<form name='game_system' action='event_submit_form.php' method='post'>"; echo "<select name='game_system' align=center style='width:150px;margin:5px 0 5px 0;'>"; echo "<option value=''>Chose a Game System</option>"; while($row_game = mysql_fetch_array($result)) { echo "<option value=''>".$row_game['System']."</option>"; } echo "</form>"; mysql_close($con); ?> </td> </tr> </table> Dear Support, Here is my code: <?php if ( strtolower($_SERVER['REQUEST_METHOD']) === 'post' ) { $name = isset($_POST['name]) ? htmlspecialchars($_POST['name']) : ""; $area = isset($_POST['area']) ? htmlspecialchars($_POST['area']) : ""; $choice = isset($_POST['choice ']) ? htmlspecialchars($_POST['choice ']) : ""; //Do Others } ?> <form class="customersForm" method="post"> <div class=""> <p>Name<br /> <select style="width:120px;" name="name"> <?php $sql = "select * from `name_info` order by `name`"; $query = mysql_query($sql); $dd = '<option>Name</option>'; while($row = mysql_fetch_object($query)) { $dd .= '<option>'.$row->name.'</option>'; } echo $dd; ?> </select> </p> </div> <div class=""> <p>Area<br /> <select style="width:120px;" area="area"> <?php $sql = "select * from `area_info` order by `area`"; $query = mysql_query($sql); $dd = '<option>Area</option>'; while($row = mysql_fetch_object($query)) { $dd .= '<option>'.$row->area.'</option>'; } echo $dd; ?> </select> </p> </div> <div class=""> <p>Choice<br /> <select style="width:120px;" choice="choice"> <?php $sql = "select * from `choice_info` where `name`='".$name."' and `area`='".$area."' order by `choice`"; $query = mysql_query($sql); $dd = '<option>Choice</option>'; while($row = mysql_fetch_object($query)) { $dd .= '<option>'.$row->choice.'</option>'; } echo $dd; ?> </select> </p> </div> ......//Others input fields ...some text fields ... </ form> I have the above code, where I would like to show the choice Drop-down box, depends on $name and $area match of the choice_info table. $name field and $area field needs to have any dependency and straight from the MySQL table. But, choice needs to depend on $name & $area. How can I do it without much using Javacript? I do not mind to use JavaScript, but prefer to minimal. By the way, I will have some other input fields too. It's an input form but, one drop-down box will be depends on two others choice. Thanks for your help. I need some help with the query for a form that selects values across multiple columns, and allow users to select multiple values in several columns. http://brinsterinc.com/tpa/tpasearch.php I assume you build the where clause for the sql by determining if there is an option value has been selected in the single-value select boxes. But how do I handle the multi-select list boxes? I'm desperate for help! Need to get somewhere with this over the weekend! TIA! Last Christmas my wife bought me a book on html and css because I said that I have always wanted to write a website. Over the last 10 months I have really enjoyed learning web design and have progressed to try and learn php and using myPHPadmin databases.
I am now trying to write a private message function. I've got a members database and a conversation database. I am trying to filter out whether a private message is 'read' or 'unread', but whatever I try it is still listing all messages under both options. I've spent 48 hours staring at this bit of code. Can anyone see what I have done wrong? The relevant (and self-explanatory) fields from my members database a id username member_first_name member_last_name The relevant fields from my conversation database a id id2 (always set as '1' to count messages in a conversation) member1 (the initial sender of the first message) member2 (the initial recipient of the first message) read1 (member1 has read this message default to yes when message sent and to no when message received) read2 (member2 has read this message default to yes when message sent and to no when message received) removed1 (member1 has deleted this message from their record) removed2 (member2 has deleted this message from their record) time (timestamp) <?php $query1 = DB::getInstance()->query("SELECT c1.id, c1.title, c1.time, c1.removed1, c1.removed2, count(c2.id) AS reps, m.id as memberid, m.username m.member_first_name, m.member_last_name FROM conversation as c1, conversation as c2, members as m WHERE ((c1.member1='{$logid}' AND c1.read1='No' AND c1.removed1='No' AND m.id=c1.member2) OR (c1.member2='{$logid}' AND c1.read2='No' AND c1.removed2='No' AND m.id=c1.member1)) AND c1.id2='1' AND c2.id=c1.id GROUP BY c1.id ORDER BY c1.id DESC"); $query2 = DB::getInstance()->query("SELECT c1.id, c1.title, c1.time, c1.removed1, c1.removed2, count(c2.id) as reps, m.id as memberid, m.username, m.member_first_name, m.member_last_name FROM conversation as c1, conversation as c2, members as m WHERE ((c1.member1='{$logid}' AND c1.read1='Yes' AND c1.removed1='No' AND m.id=c1.member2) OR (c1.member2='{$logid}' AND c1.read2='Yes' AND c1.removed2='No' AND m.id=c1.member1)) AND c1.id2='1' AND c2.id=c1.id GROUP BY c1.id ORDER BY c1.id DESC"); ?> UNREAD MESSAGES (<?php echo intval($query1->count()); ?>) <br> READ MESSAGES (<?php echo intval($query2->count()); ?>)I've tried running through things in a logical path: UNREAD MESSAGES member1 = logged in user read1 = No removed1 = No members.id = member2 OR member2 = logged in user read2 = No removed2 = No members.id = member1 READ MESSAGES member1 = logged in user read1 = Yes removed1 = No members.id = member2 OR member2 = logged in user read2 = Yes removed2 = No members.id = member1 I can't understand how if 'read1 = yes and the logged in user is member1, why they are being counted in the unread list. Can anyone see what I have done wrong? Edited by MartynLearnsPHP, 15 November 2014 - 08:05 AM. Hello i try to explain my situation, I have a dynamic table so i need to build a dynamic radiobutton list and build a dynamic sql req. First of all i build my table with radio button in a while So the radio button is named rdYanViau ( in the html it's working no prob with that ) Quote $name = $row2['FirstName'].$row2['LastName']; Quote <input type="radio" name="rd<?php echo $name; ?>" value="1"> Quote <input type="radio" name="rd<?php echo $name; ?>" value="2"> And in the same while i build a portion of my dynamic sql like that Quote $valueDeclare .= $row2['FirstName'].$row2['LastName'].', '; So in my insert this variable give me the FieldName and in the same while i build my $_POST variable for my sql sentence Quote $valueRadio .= "'".'".$_POST['."'".'rd'.$row2['FirstName'].$row2['LastName']."'".']."'."', "; This value is '".$_POST['rdYanViau']."' After that i build my sql with those 2 variables, the problem is when i execute my sql insert where he's supose to insert my rdButton value ... it's insert the string '".$_POST['rdYanViau']."' who give me a 0 in the table, he's not getting the value of '".$_POST['rdYanViau']."' he's inserting the string in the table. Here's the echo of my sql sentence : Quote INSERT INTO sondage (idSondage, username, idMatch, YanViau, YanViau2, YanViau3) VALUES (NULL , 'admin', '1', '".$_POST['YanViau']."', '".$_POST['YanViau2']."', '".$_POST['YanViau3']."') my echo should look like : Quote INSERT INTO sondage (idSondage, username, idMatch, YanViau, YanViau2, YanViau3) VALUES (NULL , 'admin', '1', '1', '2', '1') How i can build this dynamic sentence and have the radiobutton value and not the string value ... I hope you can understand my problem. Yan. Hey Guys, I'm building a site and I need a drop down menu created dynamicly.... This is the flat html code Code: [Select] <div class="art-nav"> <div class="l"></div> <div class="r"></div> <ul class="art-menu"> <li><a href="URL 1"><span class="l"></span><span class="r"></span><span class="t">TOP LEVEL</span></a> <ul> <li><a href="URL 1">SUB CAT 1</a></li> <li><a href="URL 2">SUB CAT 2</a></li> <li><a href="URL 3">SUB CAT 3</a></li> </ul> </li> <li class="art-menu-li-separator"><span class="art-menu-separator"></span></li> <li><a href="URL 5"><span class="l"></span><span class="r"></span><span class="t">Contact Us</span></a></li> </ul> </div> This is the code that shows a dyamic code, but not in the menu... <?php wpsc_start_category_query(array('category_group'=> get_option('wpsc_default_category'), 'show_thumbnails'=> get_option('show_category_thumbnails'))); ?> <a href="<?php wpsc_print_category_url();?>" class="wpsc_category_link"><?php wpsc_print_category_name();?></a> | <?php wpsc_print_subcategory(); ?> <?php wpsc_end_category_query(); ?> Here's my build a querty code... Code: [Select] $sql = "UPDATE $tablename SET DIST_PART_NUM = '$dist_part_num', DIST_PUB = '$dist_pub', MFR_PART_NUM = '$mfr_part_num', MFR_PUB = '$mfr_pub', ITEM_DESC = '$item_desc', ITEM_STD_DESC = '$item_std_desc', ITEM_COPY = '$item_copy', COST = '$cost', GP_MULT = '$gp_mult', ITEM_IMAGE = '$item_image', ITEM_URL = '$item_url', COUNTRY_OF_ORIG = '$country_of_orig', CATEGORY_ID = '$category_id', PICGROUP_KEY = '$picgroup_key', UPC_CODE = '$upc_code', LEADTIME = '$leadtime', UNITS = '$units', LENGTH = '$length', WIDTH = '$width', HEIGHT = '$height', WEIGHT = '$weight', FLAG_HAZARDOUS = '$flag_haz', FLAG_LTL = '$flag_ltl', FLAG_NON_RETURNABLE = '$flag_non', CAMPAIGN_KEY = '$campaign_key', "; foreach($atr as $key => $value) { $sql .= $value . "='" . addslashes($_POST[$value]) . "',"; } $sql2 = rtrim($sql,","); $sql2 .= " WHERE DIST_PART_NUM = '$partnumber' OR MFR_PART_NUM = '$partnumber'"; Now the query get's built 100% fine that's not the issue... my issue is that sine if the table fields are named something like #_of_shelves... and the # sign causes a MySQL error... You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 26 How can i allow for the # sign, or any other character that can cause issues like () . , * ~ etc.... i tried encompassing the field name with single quotes 'fieldname' and with those slanted ones `tablename` but that did not help. Any ideas? Thanks! I'm trying to build a search function that will search all columns in a table. Here is what I've got: Code: [Select] if (isset($_POST['submitted'])) { $q = "SELECT * FROM children "; if(isset($_POST['query'])) { $q .= "WHERE "; $all = "SELECT * FROM children WHERE 1"; $r_all = mysqli_query($dbc, $all); while ($field = $r_all->fetch_field()) { // Get field headers for building query $f_name = "{$field->name} LIKE {$_POST['query']},:"; // Build query with search string $fn = explode(":",$f_name); // Need to convert $f_name to an array but this does not convert it to a single array but multiple arrays $q .= implode("OR", $fn); // Need to insert OR for the db query } // End while ($field = $r_all->fetch_field()) } // End if(isset($_POST['query'])) } // End if (isset($_POST['submitted'])) The explode function is what is not working for me. It gives me this (sam is the search string I entered into the form): Code: [Select] Array ( [0] => child_id LIKE sam, [1] => ) Array ( [0] => first_name LIKE sam, [1] => ) Array ( [0] => second_name LIKE sam, [1] => ) Array ( [0] => last_name1 LIKE sam, [1] => ) Array ( [0] => last_name2 LIKE sam, [1] => ) Array ( [0] => gender LIKE sam, [1] => ) Array ( [0] => dob LIKE sam, [1] => ) so instead of getting one array with each string being a value I get multiple arrays. Any ideas? Right, First time on this site but hopefully I can figure out what im doing wrong. I am currently making a real time chat database for my website and have been having an issue with the coverting of string to emote image links. Code: [Select] function Smiley($texttoreplace) { $smilies=array( ':)' => "<img src='images/emotes/smile.gif'/>", ':(' => "<img src='images/emotes/sad.gif'/>", '>:(' =>"<img src='images/emotes/angry.gif'/>", ':o'=> "<img src='images/emotes/shocked.gif'/>", 'fuck'=>"$#$%", 'Fuck'=>"&$#@" ); $texttoreplace=strtr($texttoreplace, array_keys($smilies)); return $texttoreplace; } I Have even tried Code: [Select] $texttoreplace=str_replace(array_keys($smilies), array_values($smilies), $texttoreplace); but that didnt seem to work either. Here is my full code. Code: [Select] <?php include "connect.php"; $getnummessages="SELECT COUNT(*) as messagecount from chatmessages"; $getnummessages2=mysql_query($getnummessages) or die("Yay, Jump off cliff"); $getnummessages3= mysql_result($getnummessages2, 0); if($getnummessages3>21) { $startrow=$getmessages3-20; } else { $startrow=0; } $getmsg="SELECT name, message from chatmessages order by postime ASC limit $startrow,$getnummessages3"; $getmsg2=mysql_query($getmsg) or die(mysql_error()); while($getmsg3=mysql_fetch_array($getmsg2)) { $message=Smiley($message);//should make smiley here but not working....hmmmm print "<font color='red'><b>$getmsg3[name]:</b></font> $getmsg3[message]<br>"; } function Smiley($texttoreplace) { $smilies=array( ':)' => "<img src='images/smile.gif'>", ':angry' =>"<img src='images/angry.gif'>", ':o'=> "<img src='images/shocked.gif'>", 'fuck'=>"$#$%", 'Fuck'=>"&$#@" ); $texttoreplace=str_replace(array_keys($smilies), array_values($smilies), $texttoreplace); return $texttoreplace; } //this is my refresh script below ?> <script> setTimeout("window.location.replace('chatlog.php')",4000); </script> Any help would be great, been looking at this code for a while now so some fresh eyes would be great. Thanks, Score 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. Hello all,
Based on the suggestion of you wonderful folks here, I went away for a few days (to learn about PDO and Prepared Statements) in order to replace the MySQLi commands in my code. That's gone pretty well thus far...with me having learnt and successfully replaced most of my "bad" code with elegant, SQL-Injection-proof code (or so I hope).
The one-and-only problem I'm having (for now at least) is that I'm having trouble understanding how to execute an UPDATE query within the resultset of a SELECT query (using PDO and prepared statements, of course).
Let me explain (my scenario), and since a picture speaks a thousand words I've also inlcuded a screenshot to show you guys my setup:
In my table I have two columns (which are essentially flags i.e. Y/N), one for "items alreay purchased" and the other for "items to be purchased later". The first flag, if/when set ON (Y) will highlight row(s) in red...and the second flag will highlight row(s) in blue (when set ON).
I initially had four buttons, two each for setting the flags/columns to "Y", and another two to reverse the columns/flags to "N". That was when I had my delete functionality as a separate operation on a separate tab/list item, and that was fine.
Now that I've realized I can include both operations (update and delete) on just the one tab, I've also figured it would be better to pare down those four buttons (into just two), and set them up as a toggle feature i.e. if the value is currently "Y" then the button will set it to "N", and vice versa.
So, looking at my attached picture, if a person selects (using the checkboxes) the first four rows and clicks the first button (labeled "Toggle selected items as Purchased/Not Purchased") then the following must happen:
1. The purchased_flag for rows # 2 and 4 must be switched OFF (set to N)...so they will no longer be highlighted in red.
2. The purchased_flag for row # 3 must be switched ON (set to Y)...so that row will now be highlighted in red.
3. Nothing must be done to rows # 1 and 5 since: a) row 5 was not selected/checked to begin with, and b) row # 1 has its purchase_later_flag set ON (to Y), so it must be skipped over.
Looking at my code below, I'm guessing (and here's where I need the help) that there's something wrong in the code within the section that says "/*** loop through the results/collection of checked items ***/". I've probably made it more complex than it should be, and that's due to the fact that I have no idea what I'm doing (or rather, how I should be doing it), and this has driven me insane for the last 2 days...which prompted me to "throw in the towel" and seek the help of you very helpful and intellegent folks. BTW, I am a newbie at this, so if I could be provided the exact code, that would be most wonderful, and much highly appreciated.
Thanks to you folks, I'm feeling real good (with a great sense of achievement) after having come here and got the great advice to learn PDO and prepared statements.
Just this one nasty little hurdle is stopping me from getting to "end-of-job" on my very first WebApp. BTW, sorry about the long post...this is the best/only way I could clearly explaing my situation.
Cheers guys!
case "update-delete": if(isset($_POST['highlight-purchased'])) { // ****** Setup customized query to obtain only items that are checked ****** $sql = "SELECT * FROM shoplist WHERE"; for($i=0; $i < count($_POST['checkboxes']); $i++) { $sql=$sql . " idnumber=" . $_POST['checkboxes'][$i] . " or"; } $sql= rtrim($sql, "or"); $statement = $conn->prepare($sql); $statement->execute(); // *** fetch results for all checked items (1st query) *** // $result = $statement->fetchAll(); $statement->closeCursor(); // Setup query that will change the purchased flag to "N", if it's currently set to "Y" $sqlSetToN = "UPDATE shoplist SET purchased = 'N' WHERE purchased = 'Y'"; // Setup query that will change the purchased flag to "Y", if it's currently set to "N", "", or NULL $sqlSetToY = "UPDATE shoplist SET purchased = 'Y' WHERE purchased = 'N' OR purchased = '' OR purchased IS NULL"; $statementSetToN = $conn->prepare($sqlSetToN); $statementSetToY = $conn->prepare($sqlSetToY); /*** loop through the results/collection of checked items ***/ foreach($result as $row) { if ($row["purchased"] != "Y") { // *** fetch one row at a time pertaining to the 2nd query *** // $resultSetToY = $statementSetToY->fetch(); foreach($resultSetToY as $row) { $statementSetToY->execute(); } } else { // *** fetch one row at a time pertaining to the 2nd query *** // $resultSetToN = $statementSetToN->fetch(); foreach($resultSetToN as $row) { $statementSetToN->execute(); } } } break; }CRUD Queston.png 20.68KB 0 downloads Hey guys,
My problem is, iam loading with mysql_fetch_array a table from my database and draw it into my website page.
The table is a user table which has an id, user, password and rights(Admin, Mod , User).
Only the rights are given out as <select> </select> boxes with the 3 options(Admin, Mod , User).
And i also have 1 more column which has for each row a href to a new site with the id of the array_index as paramter.
My Problem is i want to know which select box was changed and which option is selected so i can change the rights in my database of this user with the right id.
At the moment i cant post the code in here cause i have a problem with my laptop now.
I hope you can help me,
Thank you
Edited by Kandey, 30 October 2014 - 02:28 PM. Hi There, Is there any way that I can get a select box to auto-select the value from a SQL query? For example, if I have a select box like this: Dave,Jon,Simon,Fred And a select statement that brings back the value of Fred then the select box (in HTML) would: <select name='people'><option>Dave</option><option>Jon</option><option>Simon</option><option selected='selected'>Fred</option></select> Same as if the name was Dave, or Simon etc etc. Hope that makes sense? Cheers Matt Hi I am trying to have the following as an example: Code: [Select] <select name="test[]" multiple="multiple">options here</select> <select name="test[]" multiple="multiple">options here</select> Then using $_POST['test'] to grab the boxes in the array. I want to then loop over each box so for example: Code: [Select] $boxes = $_POST['test']; foreach ( $boxes as $box ) // now here i would of expected $box to be an array of the options, } but it's not working like this, all the options from all submitted select boxes come in one array so I cannot distinguish which select box in the array they relate to, is there a way to do this?? Hello, I have the following function function make_agent_drop($dropname,$parent=''){ $agents = mysql_query("SELECT * FROM ad_category WHERE cat_status='1' AND parent_id='".(is_numeric($parent)?$parent:"0")."'") or die(mysql_error()); $anum = mysql_num_rows($agents); if($anum>0){ $agentdrop='<select style="width:150px; height:20px; margin-left:100px; font-size:11px;" name="'.$dropname.'" id="'.$dropname.'" class="text" '.(is_numeric($parent)?'':'onchange="update_subcatdrop($(this).val());').'"> <option value="0">Select a Category</option>'; while($row= mysql_fetch_array($agents)){ $agentdrop.='<option value="'.$row['cat_id'].'">'.$row['cat_name'].'</option>'; } $agentdrop.='</select>'; }else{ $agentdrop= 'No '.(is_numeric($parent)?'Sub':'').'Categories Found.'; } return $agentdrop; ; } I creates a drop down from database cats and sub cats.. I am trying to figure out how to add a submit button to dynamically appear when it displays the sub category... Thanks! Dan 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. hello. i have a question for you. say i have a group of tick boxes and i select a couple. would i put them in to the database as varchar ? like this: id varchar 1 1, 2, 3 or id varchar 1 '1', '2', '3' then my next question is how would i use them. i guess i would explode them or something. the thing is, i have some code that currently pull 1 item from the database (using varchar) and echos it fine but when i add more i get nothing back. thanks rick I'm having trouble getting the dynamic data from my <select> menus to write into my MYSQL database. Can anyone see what I'm doing wrong here? First post btw The output looks like this, which is obviously wrong: Code: [Select] <html> <head> </head> <link rel="stylesheet" type="text/css" href="./css/newuser.css" /> <body> <?php session_start(); require 'default.inc.php'; ?> <?php if (isset($_POST['amount'])): $host = 'localhost'; $user = 'user'; $pass = 'password'; $conn = mysql_connect($host, $user, $pass); if (!$conn) { exit('<p>Unable to connect to the database server</p>'); } if (!@mysql_select_db('spikesusers')) { exit('<p>Unable to locate the database</p>'); } $locationname = $_POST['donor']; $donorid = mysql_query("SELECT id FROM donors WHERE locationname='$locationname'"); $amount = $_POST['amount']; $year = $_POST['year']; $type = $_POST['type']; $typeid = mysql_query("SELECT id FROM donationtype WHERE type='$type'"); $player = $_POST['player']; //$playerid = mysql_query("SELECT id FROM players WHERE $sql = "INSERT INTO donations SET donorid='$donorid', amount='$amount', yearofdonation='$year', typeid='$typeid'"; mysql_query($sql); ?> <div class='standard'> <h1>Donation Management</h1> <?php if ($sql) { echo "New donation added "; echo "<p></p>"; echo "<a href=managedonations.php>Back to donation management</a>"; exit(); } else { echo "Error adding new donation"; echo "<a href=adddonation.php>Try again</a>"; exit(); } ?></div> <?php else: $host = 'localhost'; $user = 'user'; $pass = 'pass'; $conn = mysql_connect($host, $user, $pass); if (!$conn) { exit('<p>Unable to connect to the database server</p>'); } if (!@mysql_select_db('spikesusers')) { exit('<p>Unable to locate the database</p>'); } $donor=@mysql_query('SELECT id, locationname FROM donors'); ?> <div class='standard'> <h1>Donation Management</h1> <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post"> <label>Donor: <select class="text" name="donor"> <option value=new>Add a new donor...</option> <?php while ($donors=mysql_fetch_array($donor)) { $donorname=$donors['locationname']; echo "<option value='<?php echo $donorname;?>'>$donorname</option>"; //echo "<option value='hi'>hi</option>"; } ?> </option> </select> </label><br /> <label>Amount: <input class="text" type="text" name="amount" class="text" /></label><br /> <label>Year of donation: <select class="text" name="year"> <option value='2011'>2011</option> <option value='2010'>2010</option> <option value='2009'>2009</option> </select> </label><br /> <?php $player=@mysql_query('SELECT id, firstname, lastname FROM players'); ?> <label>Player: <select class="text" name="player"> <option value="player" selected="selected"></option> <?php while ($players=mysql_fetch_array($player)) { $playerfirstname=$players['firstname']; $playerlastname=$players['lastname']; echo "<option value=player>$playerfirstname $playerlastname</option>"; } ?> </select> </label><br /> <?php $type=@mysql_query('SELECT id, type FROM donationtype'); ?> <label>Donation type: <select class="text" name="type"> <?php while ($types=mysql_fetch_array($type)) { $donationtype=$types['type']; echo "<option value=type>$donationtype</option>"; } ?> </select> </label><br /> <input type="submit" value="SUBMIT" class="buttons"/> <input type="button" name="Cancel" value="CANCEL" onclick="window.location = 'managedonations.php'" class="buttons"/> </form> </div> <?php endif; ?> </body> </html> Hello, I had 8 select boxes(dropdowns) in a form. Its like a search kind of implementation in the website. I don't know what the user selects, he may choose different select boxes, any number of select boxes. So, based upon the user selection, I need to generate the data. The data fields to be generated would be almost same. So, How would I know what the user selection is and how many select boxes has been selected and how could I generate different data based upon selected boxes. I had to make a small note abt this, that the data generation fields may change for some of the user select combinations, but most of the result fields would be same. so, can you please help me out, how to do, how to make different combination data generations, because, i had 8 fields, i had to make 8! combinations, that would result in a big code. Hello all, I have three text fields ( hosteladmissionnumber,branch & Semester) and three text boxes in a form. When i provide the hostel admission number , the corresponding branch semester must be acquired from the registrationtable in DB and fill it in text boxes. How can i do it? any help would be appreciated. Thanks. I have pasted the code below. [syntax=php] <?php session_start(); $hostad=$_POST['hosteladmissionno']; $sem=$_POST['student_name']; $sem=$_POST['semester']; $con=mysql_connect('localhost','root',''); if(!$con) { die('Unable to connect'.mysql_error()); } mysql_select_db('hostel',$con); //i have to insert the hosteladmission in payment too..but no need to insert semester and branch $r1="INSERT INTO payment(hosteladmissionno) values ('$hostad')"; mysql_close($con); ?> /HTML PART <form action='payment.php' method='POST' name='form1'> <center> <table> <tr><td><b>Admission No:</b></td><td><input type='text' name='hosteladmissionno'></td></tr> <tr><td><b>Student Name:</b></td><td><input type='text' name='student_name'></td></tr> <tr><td><b>Semester:</b></td><td><input type='text' name='semester'></td></tr> [/syntax] |