Bill Withers Posted August 8, 2012 Share Posted August 8, 2012 Hello, I am trying to get a php script to do some things and I need some help. First- is this even possible in PHP alone Second - if it is I sure could use some syntax help. PHP 5.2.17 Mysql 5.1.57 populate 12 drop down boxes // I have given 3 examples here =------------------------------------ A form submit page with 12 mysql populated select drop down boxes Each category has its own table. each table has a id auto increment and name field with each tables first entry as random and the rest of the names to follow. ie Table.Places = $query1 ----------- ID name ---------- 1. Random 2. burnside 3. davenport 4. mumford 5. kenny 6. freer etc Table.color = $query2 ------------ ID name ---------- 1. Random 2. Blue 3. Red 4. Orange Table.state = $query3 -------------- ID name -------------- 1. Random 2. On 3. Off //----------------------------------------------------------------------------------------------------------- //The way I get the drop down populated is: and this part works ok //------------------------------------------------------------------------------------------------------------ $result = mysql_query( "SELECT name FROM places" ) or die("SELECT Error: ".mysql_error()); $options="Select"; while ($row=mysql_fetch_array($result)) { $querry1=$row["name"]; $options.="<OPTION VALUE=\"$query1\">".$query1.'</option>'; //--------------------------------------------------- Next the user selects Random or item in each Drop Down box and hits send. if the selection is Random then the result is a random item displayed if one of the other names are picked then that name is displayed. I want to keep the selections dynamic from the DB so I don't want to hard code in a variable for each name so maybe the choices are: +--------+ +---------+ +--------+ | Random| | Blue | | On | +--------+ +---------+ +--------+ when the page is submitted to tabulate.php ------------------------------------------------------------------------------------ // I know that the syntax is wrong here, This is where i could use some help. //I have put a error check to see if I am passing anything to tabulate.php like this //<?php //var_dump($_POST); //echo '<hr />'; //?> //But I get nothing returned. ----------------------------------------------------------------- If $query1 == [Random] then $query1 = "SELECT name FROM courses ORDER BY RAND()LIMIT 1"; $result = mysql_query($query) or trigger_error(mysql_error()." ".$query1); $row = mysql_fetch_assoc($result); $name = $row["name"]; Echo $name Else Echo $query1 if value Random is selected from $query2 ETC.. etc... Many, Many thanks in advance Bill Quote Link to comment Share on other sites More sharing options...
Psycho Posted August 8, 2012 Share Posted August 8, 2012 There's a much simpler way. Create a function to create the select lists. So, you just need to run the query with the IDs and the names and pass the result into the function to create the options. Further, build the function to first create all the non-random choices putting the IDs into an array. Once all the options have been created choose a random ID from the list and create the Random option using that ID and prepend that option to the beginning. Then when the user chooses random, just use the selected ID that was used for the Random optino rather than having to run another DB query. Quote Link to comment Share on other sites More sharing options...
Bill Withers Posted August 8, 2012 Author Share Posted August 8, 2012 Woooosh That was the sound of that going right over my head.. Very interesting though if I understand you. so make the word random in the selection box loaded and ready to go when displayed? so if that is chosen its all set to echo out a variable? am I getting your drift? Sorry I am very very rusty Quote Link to comment Share on other sites More sharing options...
Psycho Posted August 8, 2012 Share Posted August 8, 2012 Here's some sample code using two tables for illustrative purposes. This is not tested, but should give you an idea of where to start. The key to this approach is that you will simply use the ID passed from the form. The code below will automatically create the select lists for you along with a "Random" option that will have the value of a random ID from that list. <?php //Function to create the options list. //The $dataResult is expected to be a DB //Result set with fields named 'id' and 'name' function createOptions($dataResult) { $optionsIDs = array(); $optionsHTML = ''; //Process result set into options while($row = mysql_fetch_assoc($result)) { $optionsIDs[] = $row['id']; $optionsHTML .= "<option value='{$row['id']}'>{$row['name']}</option>\n"; } //Get a random ID from the records $randomID = $optionsIDs[array_rand($optionsIDs)]; $optionsHTML = "<option value='{$randomID}'>Random</option>\n" . $optionsHTML; return $optionsHTML; } $query = "SELECT id, name FROM Places"; $result = mysql_query($query); $placesOptions = createOptions($result); $query = "SELECT id, name FROM color"; $result = mysql_query($query); $colorOptions = createOptions($result); ?> Places: <select name="places"> <?php echo $placesOptions; ?> </select> Colors: <select name="color"> <?php echo $colorOptions; ?> </select> Quote Link to comment Share on other sites More sharing options...
Bill Withers Posted August 9, 2012 Author Share Posted August 9, 2012 Hey Psycho, Thanks for replying sorry for the delay. I have played a bit with this but keep getting unrefined variable and unrefined index with the following. maybe I am just missing something small <?php mysql_connect ("localhost", "root", "xxx"); $dataResult="op1"; @mysql_select_db($dataResult) or die( "Unable to select database"); //Function to create the options list. //The $dataResult is expected to be a DB //Result set with fields named 'id' and 'name' function createOptions($dataResult) { $optionsIDs = array(); $optionsHTML = ''; //Process result set into options while($row = mysql_fetch_assoc($result)) { $optionsIDs[] = $row['id']; $optionsHTML .= "<option value='{$row['id']}'>{$row['name']}</option>\n"; } //Get a random ID from the records $randomID = $optionsIDs[array_rand($optionsIDs)]; $optionsHTML = "<option value='{$randomID}'>Random</option>\n" . $optionsHTML; return $optionsHTML; } $query = "SELECT id, name FROM places"; $result = mysql_query($query); $placesOptions = createOptions($result); $query = "SELECT id, name FROM color"; $result = mysql_query($query); $colorOptions = createOptions($result); ?> Places: <select name="places"> <?php echo $placesOptions; ?> </select> Colors: <select name="color"> <?php echo $colorOptions; ?> </select> Quote Link to comment Share on other sites More sharing options...
Bill Withers Posted August 9, 2012 Author Share Posted August 9, 2012 sorry the relevant errors are at line 16 -- while($row = mysql_fetch_assoc($result)) and line 22 --$randomID = $optionsIDs[array_rand($optionsIDs)]; Quote Link to comment Share on other sites More sharing options...
Christian F. Posted August 9, 2012 Share Posted August 9, 2012 It's "undefined", not "unrefined". If you check the dictionary, you'll see that there's a quite large difference in meaning between those two words. Should even help you figure out what the "problem" is, in fact. Quote Link to comment Share on other sites More sharing options...
Psycho Posted August 9, 2012 Share Posted August 9, 2012 sorry the relevant errors are at line 16 -- while($row = mysql_fetch_assoc($result)) and line 22 --$randomID = $optionsIDs[array_rand($optionsIDs)]; That first line would not generate an error regarding an undefined index. There's a reason the PHP errors provide all the information that they do - they are useful in finding the actual error. By trying to parse the error down to what you think is relevant only hinders our ability to help. I only provided "sample code". I do my best to ensure it is working code, but I don't take the time to create databases and sample data just to test code I am providing to people here. Generally, the code I provide is more of a general guideline on how to solve a problem. My expectation is that the recipient will do the debugging and fixing of any typos. After reviewing the code I do see some errors: 1. The options being created were overwriting the variable $optionsHTML instead of appending to it 2. The while loop was using the the wrong variable -it should be the one passed to the function Try the following. If it doesn't work try to fix the errors. If you can't fix the errors provide the entire error messages received <?php $dataResult="op1"; mysql_connect ("localhost", "root", "xxx") or die( "Unable to connect to database"); @mysql_select_db($dataResult) or die( "Unable to select database"); //Function to create the options list. //The $dataResult is expected to be a DB //Result set with fields named 'id' and 'name' function createOptions($dataResult) { if(!$dataResult || mysql_num_rows($dataResult)) { //No records included for option list return "<option value=''>EMPTY</option>\n"; } $optionsIDs = array(); $optionsHTML = ''; //Process result set into HTML options while($row = mysql_fetch_assoc($dataResult)) { $optionsHTML .= "<option value='{$row['id']}'>{$row['name']}</option>\n"; $optionsIDs[] = $row['id']; } //Get a random ID from the records $randomID = $optionsIDs[array_rand($optionsIDs)]; $optionsHTML = "<option value='{$randomID}'>Random</option>\n" . $optionsHTML; return $optionsHTML; } $query = "SELECT id, name FROM places"; $result = mysql_query($query); $placesOptions = createOptions($result); $query = "SELECT id, name FROM color"; $result = mysql_query($query); $colorOptions = createOptions($result); ?> Places: <select name="places"> <?php echo $placesOptions; ?> </select> Colors: <select name="color"> <?php echo $colorOptions; ?> </select> Quote Link to comment Share on other sites More sharing options...
Bill Withers Posted August 9, 2012 Author Share Posted August 9, 2012 It's "undefined", not "unrefined". If you check the dictionary, you'll see that there's a quite large difference in meaning between those two words. Should even help you figure out what the "problem" is, in fact. What are you, Like twelve? Seriously, you are going to troll my thread over a mistype? I guess I can understand what the F in your name stands for. Thanks all for the PHP enlightenment at this fine establishment Quote Link to comment Share on other sites More sharing options...
Christian F. Posted August 9, 2012 Share Posted August 9, 2012 I was not trolling, I was simply trying to help as it appeared you didn't understand the error message. I have no way of knowing how fluent you are in English, after all. Especially not when the same mistype happens twice in a row, in exactly the same manner, and with a completely different meaning than what it should have read. We recommend copy-pasting error messages for a reason, and that is to (amongst other things) avoid misunderstanding such as these. I recommend utilizing that function the next time. PS: Trying to insult me will not make people, me especially, more inclined towards helping you. It's your choice whether or not you want to perceive my words as insults, but dropping down to that level yourself is only hurting you. Quote Link to comment Share on other sites More sharing options...
Bill Withers Posted August 10, 2012 Author Share Posted August 10, 2012 That's all well and good. Maybe its the elitist tone of your obtuse answers here, I don't know. in any case. good day to you sir. Quote Link to comment Share on other sites More sharing options...
Bill Withers Posted August 10, 2012 Author Share Posted August 10, 2012 Thanks again Psycho, I can see what you were going for there. Of course this will end in a empty set but the streamlined process is duly noted and appreciated. As to the original question, is it possible in php to do what I would like the original layout to do? Thanks again Quote Link to comment Share on other sites More sharing options...
Psycho Posted August 10, 2012 Share Posted August 10, 2012 As to the original question, is it possible in php to do what I would like the original layout to do? I guess your original question was not very clear. On rereading your first post I think maybe you are wanting the number of select fields and the processing to be dynamic based upon the number of tables you want utilized. All you need to do is create one block of code to create ONE select field and create one block of code to process that data. Then just create an array of the tables and put your blocks within a foreach loop. Have have written and tested the following code against two sample tables. I think this is what you are trying to achieve. If not, please be more specific. To test this you should only need to modify the array at the very top to ensure you have a valid table name as the key of each item and an associated label. Each table listed must have fields labeled 'id' and 'name'. <?php //Create array of table names as keys and labels as values $tables = array( 'Places' => 'Place', 'color' => 'Color'); //Function to create the options list. //The $dataResult is expected to be a DB //Result set with fields named 'id' and 'name' function createOptions($dataResult) { $optionsIDs = array(); $optionsHTML = ''; //Process result set into options //echo mysql_num_rows($dataResult); while($row = mysql_fetch_assoc($dataResult)) { $optionsIDs[] = $row['id']; $optionsHTML .= "<option value='{$row['id']}'>{$row['name']}</option>\n"; } //Get a random ID from the records $randomID = $optionsIDs[array_rand($optionsIDs)]; $optionsHTML = "<option value='{$randomID}'>Random</option>\n" . $optionsHTML; return $optionsHTML; } //Connect to database mysql_connect('localhost', 'root', ''); mysql_select_db('test'); $output = ''; if(isset($_POST['selections'])) { //User submitted for, display selected vaues $output .= "<b>Your selections:</b><br>\n"; foreach($_POST['selections'] as $table => $idValue) { //Query the value based upon selected ID $query = "SELECT name FROM {$table} WHERE id = '{$idValue}' LIMIT 1"; $result = mysql_query($query); $value = mysql_result($result , 0); $output .= "{$tables[$table]}: $value<br>\n"; } $output .= "<br><br><a href=''>Change Selections</a>\n"; } else { //Display the form $output .= "<form action='' method='post'>\n"; foreach($tables as $table => $label) { $query = "SELECT id, name FROM {$table}"; $result = mysql_query($query) or die(mysql_error()); $placesOptions = createOptions($result); $output .= "{$label} \n"; $output .= "<select name=\"selections[{$table}]\">"; $output .= $placesOptions; $output .= "</select><br><br>\n"; } $output .= "<button type='submit'>Submit</button>\n\n"; $output .= "</form>\n"; } ?> <html> <head></head> <body> <?php echo $output; ?> </body> </html> Quote Link to comment Share on other sites More sharing options...
Bill Withers Posted August 10, 2012 Author Share Posted August 10, 2012 Okay, Again thanks for all the help. I got it to do what I wanted 1. populated the drop downs with data from the DB with an extra value of "Random" 2. when the options are submitted, Depending on whether the user selects a db value or the "random" value, The user is presented with the choice they picked or a random choice via a if else statement on the results page. Before I go live with it I was wanting to know if there are any security holes as far as injection exploits I should address. Should I continue on with those questions in this thread or make another? as there is a lot of sloppy code to look at Thanks Quote Link to comment Share on other sites More sharing options...
Bill Withers Posted August 10, 2012 Author Share Posted August 10, 2012 Oops, We posted at the same time. Thanks again Psycho! I will try this out as it is waaay more rational looking than what I have. I guess your original question was not very clear. On rereading your first post I think maybe you are wanting the number of select fields and the processing to be dynamic based upon the number of tables you want utilized. All you need to do is create one block of code to create ONE select field and create one block of code to process that data. Then just create an array of the tables and put your blocks within a foreach loop. Have have written and tested the following code against two sample tables. I think this is what you are trying to achieve. If not, please be more specific. To test this you should only need to modify the array at the very top to ensure you have a valid table name as the key of each item and an associated label. Each table listed must have fields labeled 'id' and 'name'. <?php //Create array of table names as keys and labels as values $tables = array( 'Places' => 'Place', 'color' => 'Color'); //Function to create the options list. //The $dataResult is expected to be a DB //Result set with fields named 'id' and 'name' function createOptions($dataResult) { $optionsIDs = array(); $optionsHTML = ''; //Process result set into options //echo mysql_num_rows($dataResult); while($row = mysql_fetch_assoc($dataResult)) { $optionsIDs[] = $row['id']; $optionsHTML .= "<option value='{$row['id']}'>{$row['name']}</option>\n"; } //Get a random ID from the records $randomID = $optionsIDs[array_rand($optionsIDs)]; $optionsHTML = "<option value='{$randomID}'>Random</option>\n" . $optionsHTML; return $optionsHTML; } //Connect to database mysql_connect('localhost', 'root', ''); mysql_select_db('test'); $output = ''; if(isset($_POST['selections'])) { //User submitted for, display selected vaues $output .= "<b>Your selections:</b><br>\n"; foreach($_POST['selections'] as $table => $idValue) { //Query the value based upon selected ID $query = "SELECT name FROM {$table} WHERE id = '{$idValue}' LIMIT 1"; $result = mysql_query($query); $value = mysql_result($result , 0); $output .= "{$tables[$table]}: $value<br>\n"; } $output .= "<br><br><a href=''>Change Selections</a>\n"; } else { //Display the form $output .= "<form action='' method='post'>\n"; foreach($tables as $table => $label) { $query = "SELECT id, name FROM {$table}"; $result = mysql_query($query) or die(mysql_error()); $placesOptions = createOptions($result); $output .= "{$label} \n"; $output .= "<select name=\"selections[{$table}]\">"; $output .= $placesOptions; $output .= "</select><br><br>\n"; } $output .= "<button type='submit'>Submit</button>\n\n"; $output .= "</form>\n"; } ?> <html> <head></head> <body> <?php echo $output; ?> </body> </html> Quote Link to comment Share on other sites More sharing options...
Bill Withers Posted August 10, 2012 Author Share Posted August 10, 2012 Here is what I have, I haven't tried your new code yet Form ----------- <form action= "results.php" method="post"> Populating the Drops ---------------------- $database="op"; mysql_connect ("localhost", "root", "xxx"); @mysql_select_db($database) or die( "Unable to select database"); $result = mysql_query( "SELECT ID, course_name FROM courses" ) or die("SELECT Error: ".mysql_error()); $options="Random"; while ($row=mysql_fetch_array($result)) { $firstvalue=$row["course_name"]; $options.="<OPTION VALUE=\"$firstvalue\">".$firstvalue.'</option>'; } $result = mysql_query( "SELECT tee FROM tee" ) or die("SELECT Error: ".mysql_error()); $options3="Random"; while ($row=mysql_fetch_array($result)) { $firstvalue=$row["tee"]; $options3.="<OPTION VALUE=\"$firstvalue\">".$firstvalue.'</option>'; } Results page ------------------- var output from the submission. The user selected Random for courses and White for tee -------------------------------------- array(12) { ["COURSES"]=> string(0) "" ["TEE"]=> string(5) "White" what to show the user ------------------------------ if ($_POST['COURSES'] === "") { $query = "SELECT course_name FROM courses ORDER BY RAND()LIMIT 1"; $result = mysql_query($query) or trigger_error(mysql_error()." ".$query); $row = mysql_fetch_assoc($result); $course = $row["course_name"]; echo $course; } else { echo ($_POST['COURSES']); } ?> </td> <td> <?php if ($_POST['TEE'] === "") { $query = "SELECT tee FROM tee ORDER BY RAND()LIMIT 1"; $result = mysql_query($query) or trigger_error(mysql_error()." ".$query); $row = mysql_fetch_assoc($result); $tee = $row["tee"]; echo $tee; } else { echo ($_POST['TEE']); } ?> Quote Link to comment Share on other sites More sharing options...
Psycho Posted August 10, 2012 Share Posted August 10, 2012 The approach you have implemented requires many more queries and is not good practice in my opinion. I gave you what I believe is a more efficient method. I'm not going to spend my time to review code which I believe is flawed to begin with. But, this is your site, so go with it if it suits you. Quote Link to comment Share on other sites More sharing options...
Bill Withers Posted August 10, 2012 Author Share Posted August 10, 2012 I agree that I think it is flawed. and as I stated I hadn't tried your code yet, I just wanted to show you what I had working if there were any other questions about the structure thanks again Quote Link to comment Share on other sites More sharing options...
Bill Withers Posted August 11, 2012 Author Share Posted August 11, 2012 Your Solution works very nice!! and it is very elegant and streamlined. Thank you very much for your time and effort!!!! Quote Link to comment Share on other sites More sharing options...
Bill Withers Posted August 15, 2012 Author Share Posted August 15, 2012 Just noticed a strange thing in firefox 12 if I go to the page that this script is on, hitting reload actually acts like you hit the submit button. only it randomizes all within the dropdowns. it does this on localhost win/xamp and on live server /linux/apache/etc chrome - 21.0.1180.79 m latest opera and IE9 all behave as you would expect, just as if you retyped the url I cant get firefox to do this with any other like scripted page I have found. what do you think? Quote Link to comment Share on other sites More sharing options...
Christian F. Posted August 15, 2012 Share Posted August 15, 2012 If you have posted any content with Fx before hitting F5, it will re-send the POST data again. Or at least/warn you about it, unless you've turned that message off. All browsers does this, btw. That's why I always use a header ('Location: ...'); die (); call after successfully parsing a POST request, so that the user won't get this F5-resend problem. Quote Link to comment Share on other sites More sharing options...
Psycho Posted August 15, 2012 Share Posted August 15, 2012 in firefox 12 if I go to the page that this script is on, hitting reload actually acts like you hit the submit button. only it randomizes all within the dropdowns. I don't follow what you mean about it randomizing all the drop-downs. Are you really talking about POSTing here? One thing I've always notice about FF is that if you have a form that you've made selections/changes to and click refresh the page reloads with the same data displayed in the fields as if the site had scripted it for sticky form fields. But, FF is doing it automatically. If you select Ctrl-F5 it will do a hard refresh. If this is what you are talking about - it is a feature of FF. You can probably work around it if you need. Using a header() after a POST is a good way to clear the data to prevent a double post, but you could probably also use it to prevent this behavior in FF. But, I see no harm in it. Quote Link to comment Share on other sites More sharing options...
Bill Withers Posted August 15, 2012 Author Share Posted August 15, 2012 In the script you have here in this thread. the drop down boxes are populated from the tables, but the first choice is random. when you hit submit it presents a random choice from that table if no other selection is made besides random. if looking at the page with FF with the dropdown boxes that say random, and hit the reload page, it presents the dropdowns with random data not the random choice as expected. just thought it was weird is all. Also, if looking at the dropdown page, if you hit show source you can see what the random choice will be when submit is selected by the string value of the ID... hehe, so it has already randomized the data before the drop downs are presented I just found that strange is all. The script works very well and uses almost nothing in resources. Thanks again Psycho.. And you as well ChristianF Quote Link to comment Share on other sites More sharing options...
Christian F. Posted August 15, 2012 Share Posted August 15, 2012 Guess I'll have to see it for myself, to be 100% sure of what's happening. Though, I still suspect some residual POST data. You're welcome, btw. Glad we could help, no matter how small it might have been. Quote Link to comment Share on other sites More sharing options...
Bill Withers Posted August 16, 2012 Author Share Posted August 16, 2012 Ok, Thanks again Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.