Prepare drop down list and use multiple times - php

I've got a database of regions for sale and I'm displaying it in a table for admins to edit the cost, whether it's for sale and who's selling it (seller). For the seller I've got a drop down list with an first option as the current owner for ease of use and then under that I just want it to list the rest of the possible users that could be sellers.
Thing is, there's a good 200 regions and I don't want to loop through every user for each region to display them in a list. Is there a way I can prepare the many 's rather than loop every time. Something like preparing the list as a string then inserting it as HTML? Wouldn't know how to do it that way if possibe.
Thanks in advance.[

let's say you make your list this way:
$str = "<select>";
$result = mysql_query("select * from sellers");
while($row=mysql_fetch_assoc($result)){
$str.= '<option value="'.$row['id'].'">'.$row['name'].'</option>';
}
$str.="";
And you just output that everywhere you want the list to appear.
Also, you don't have to put the one you want selected by default at the top, you can also add the word 'selected' to the option tag like so:
<option value='1' selected>John Doe</option>

If I understand the question correctly. You need to create an array of option tags.
$Name = array();
$q = "SELECT name FROM users";
$r = mysqli_query ($dbc, $q) or die("Error: ".mysqli_error($dbc));
while($row = mysqli_fetch_array($r)){
$Name[] = "<option value='$row[\"name\"]'>$row[\"name\"]</option>";
}
Then anytime you need that you just loop through array like so:
<select id='thisselect' name='thisselect'>
<?php
foreach($Name as $key =>$line){
echo "$line";
}
?>
</select>

All the answers are good but I suggest you to separate the logic from the content itself, instead of doing all that with concatenated strings, you should do it like this:
<select id="region" name="region">
<?php foreach($regions as $key => $region) ?>
<option value="<?php echo $key ?>"><?php echo $region ?></option>
<?php endforeach; ?>
</select>

Related

PHP dropdown menu that concatenates 2 rows from MySQL data table

Not experienced with creating forms in PHP.
I can get my form to produce a dropdown list that has one of my rows listed as an option, but as soon as I try to concatenate 2 rows together (from the same table) for option output...
a) It just doesn't work and I get errors
b) I get the first row as a single option, then my next row as a separate option.
I know there is a simple solution to this, but I am an online student just learning, and I can't seem to find a good example of the code to write it. I'm pretty sure it's an issue of quotes not being placed correctly.
MySQLTable Data:
Table Name: courses
Table Rows: course_id, course_name, max_enrolment
Sample Data: LO-COMP-8001, Intro to HTML, 20
function select_course(){
global $open;
$select = "SELECT * FROM courses";
$result = mysqli_query($open, $select);
return $result;
}
<form action="insert.php" method="post">
<dl>
<dt>Select Course</dt>
<dd><select name="course_id">
<?php // CREATE dropdown menu
$result = select_course();
while ($row = mysqli_fetch_assoc($result)) {
foreach ($row as $selection) {
echo "<option value=\"$selection\">$selection</option>";
}}
?>
</select>
</dd>
</dl>
Then there are a few more form fields such as student name and student id afterwards...
Goal Output:
course_id course-name
"LO-COMP-8001 Intro to HTML" ... as a single connected dropdown option and other remaining courses in a dropdown menu
Current Output:
LO-COMP-8001 (as an option)
Intro to HTML (as another option! ... No good)
20 (must be hidden, I need to check if course is full in another function and either allow or deny a student to enrolled etc.)
I have tried:
// output is the one mentioned above..
echo "<option value=\"$selection\">$selection</option>";
// or alternatively...
echo '<option value="'.$row['course_id'].'">'.$row['course_id'].'</option>';
But the second option creates all kinds of weird results.
This is what I am experimenting with right now...
echo '<option value="'.$row['course_id'] $row['course_name']'">'.$row['course_id'] $row['course_name'].'</option>';
But there is a bunch of issues with quotes and square brackets, and I just don't know how to format it correctly for the output.
Any assistance is appreciated.
$row holds the entire row as an associative array therefore no need for the 'foreach' loop.
function select_course(){
global $open;
$select = "SELECT * FROM courses";
$result = mysqli_query($open, $select);
return $result;
}
<form action="insert.php" method="post">
<dl>
<dt>Select Course</dt>
<dd><select name="course_id">
<?php // CREATE dropdown menu
$result = select_course();
while ($row = mysqli_fetch_assoc($result)) {?>
<option value="<?php echo $row["course_id"]; ?>"><?php echo $row["course_name"]; ?></option>
<?php }
?>
</select>
</dd>
</dl>
</form>
I was able to come up with another solution as well:
Once the foreach loop was removed, I tried cleaning up the code some... I'm not sure if this is uncommon or 'bad' style, but it does work.
$result = select_course();
while ($row = mysqli_fetch_assoc($result)) {
$course_id = $row['course_id'];
$course_name = $row['course_name'];
echo "<option value=\"$course_id\">$course_id $course_name</option>";
Results in: LO-COMP-8001 Intro to HTML as a single option, plus all my other courses in the database.

Use mysql query result in more than one place in code

I'm building a system that tracks contact lenses. I'm storing the contact lens info in a database as sometimes prices/availabilities change and i access this info from multiple points in the program. I'm trying to interface with this list using a dropdown by doing "SELECT * FROM contacts" as a query. my code looks like this :
$contact_list = mysqli_query($link, "SELECT brand FROM contacts ORDER BY brand");
Then I echo that list out in a while loop using PHP to populate the options in the dropdown.
My question is this: I have these dropdowns for each eye on the same form. So it's "Brand Right Eye"....other miscellaneous info about the right eye....then "Brand Left Eye". But ONLY the right eye is populating with the brand info because it appears first in the code. What i'm having to do is copy/paste the exact same query and do
$contact_list2 = mysqli_query($link, "SELECT brand FROM contacts ORDER BY brand");
then later if I need the dropdown again, I need to do $contact_list3..and so on. Why can i not generate a drop down using the same variable? Why does it stop responding to calling the variable after the first execution of it and is there any work around that I can implement that would allow me to not have to copy/paste the same query with a different variable association each time?
just for refernce, my php while code is this:
<select class="form-control" name = "brandOS">
<option value="0">Please Select</option>
<?php
while($row = mysqli_fetch_array($contact_list))
{
?>
<option value = "<?php echo($row['brand'])?>" name = "brandOS">
<?php echo($row['brand']) ?>
</option>
<?php
}
?>
</select>
I have this loop copy/pasted for right eye and left eye. But it only works on which ever drop down appears first in the code.
A possible solution will be more efficient in term of performance could be :
<?php
$left_eye = '<option value="0">Please Select</option>';
$rigth_eye = '<option value="0">Please Select</option>';
while($row = mysqli_fetch_array($contact_list))
{
//logic for left eye
$left_eye .= <<<HTML
<option value ="{$row['brand']}" name = "brandOS">
{$row['brand']}
</option>
HTML;
//logic for rigth eye
$rigth_eye .= <<<HTML
<option value ="{$row['brand']}" name = "brandOS">
{$row['brand']}
</option>
HTML;
}
?>
<select class="form-control" name = "brandOS">
<?php echo $left_eye ; ?>
</select>
<select class="form-control" name = "brandOS">
<?php echo $rigth_eye ; ?>
</select>
With this solution you get your result in the same while loop. If the left and right select are the same you can use the same variable.
Store the brands in an array, then you can just loop through the array.
<?php
$contact_list = mysqli_query($link, "SELECT brand FROM contacts ORDER BY brand");
$brands = array();
while($row = mysqli_fetch_array($contact_list))
{
array_push($brands, $row['brand']);
}
?>
<select class="form-control" name = "brandOS">
<option value="0">Please Select</option>
<?php
foreach($brands as $brand){
?>
<option value = "<?php echo($brand[0])?>" name = "brandOS">
<?php echo($brand[0]) ?>
</option>
<?php
}
?>
</select>
You can use a PHP array, like the SESSION one, to store values and use them across your site. Be sure you call "session_start()" method on each page you use that array, though.
//Initialize sessions
session_start();
...
//Right after getting result from query
$_SESSION['contact_list'] = $contact_list;
To use it, just be sure to call the method I told you above, and call the variable with the same syntax:
<?php
while($row = mysqli_fetch_array($_SESSION['contact_list'])) { ?>
Hope this helps.

Php mysqli Listbox

I have a list box and have 2 questions.
1st how can i still have the text to say Select a country?
2nd on my update page it displays the proper country but will not allow it to be change for it will not list any of the other countries in edit page
<?php
$sql = "SELECT countries.country_id, countries.country_name, users.user_country FROM countries, users
WHERE users.user_country = countries.country_id";
$result = query($sql);
?>
<select class="form-control input-lg box" id="country" name="country">
<?php
$i = 0;
while (($row = mysqli_fetch_assoc($result)) != false) {
?>
<option value="<?=$row["country_id"];?>"><?=$row["country_name"];?></option>
<?php
$i ++;
}
?>
Well, to have a default option not provided by your database call, you just need an HTML statement such as
<option value="">Select a country</option>
right below your <select> statement.
And we can't see your table definitions, but your SQL code seems to be picking the specific country that the user is associated with, so that there is only one country in the list. You probably need two queries: One that obtains the user's current country, and a second that obtains the entire list of countries.
After the first query, save the user's current countryid in a variable - say, $usercountryID.
Then, in your loop through the countries, compare each countryID to the user's country, like this:
while (($row = mysqli_fetch_assoc($result)) != false) {
if ($usercountryID == $row["country_id"]) $selected = " selected";
else $selected = "";
echo "<option value='{$row['country_id']}$selected>{$row['country_name']}</option>\n";
}
$selected could be defined many ways, of course, including in a conditional assignment statement. I omitted the $i counter, which isn't needed here, but, of course, you might need it later.

PHP - How do you get the values of a dropdown from SQL

Say I've got a dropdown list on my site like this:
<select>
<option value="test">Volvo</option>
<option value="icles">Saab</option>
<option value="lol">Mercedes</option>
<option value="hax">Audi</option>
</select>
But I don't want the above values, what if I want to get the values from an SQL table, how would I do this? Obviously this would be PHP but could someone give me an example?
you will have to do it like this:
first select the values:
$result = "SELECT * from table";
then you will have to foreach() those values and create your selectbox like this:
echo '<select>';
foreach($result as $res) {
echo '<option value="'.$res['somevalue'].'">' . $res['car_name'] . '</option>';
}
echo '</select>';
and you're done :D

How can I create <select> optgroups in html using data from mysql?

SO I have about 60 fields of data queried from a database. They look like this in page source:
<option>Genesis</option>
<option>Exodus</option>
<option>Leviticus</option>
For example I wanna have it so that 1-20 are a certain optgroup and then 20-60 is another. Could I do it using my format of options of would they have to be numbered like this:
<option value="1">Genesis</option>
<option value="2">Exodus</option>
<option value="3">Leviticus</option>
This is for my php class, but i dont think php is involved in making optgroups here, or is it? Thank you hope you understand my question. Hoping for help.
I pull the data from mysql using this :
//Query the database for the results we want
$query = $mysqli->query("select distinct bname as Name from kjv"); ?>
And then output it in the select dropdown box using this:
<select>
<?php while($option = $query->fetch_object()){ ?>
<option><?php echo $option->Name; ?></option>
<?php } ?>
</select>
Use:
<select>
<?php
$i=1;
while($option = $query->fetch_object()){
if($i%10==1) echo "<optgroup label='Option Group'>";
echo "<option value='$i'>".$option->Name."</option>";
$i++;
if($i%10==1) echo "</optgroup>";
}
?>
</select>
Using while loop :
$query = "SELECT * FROM example";
$result = mysql_query($query) or die(mysql_error());
foreach ($row = mysql_fetch_array($result)) {
echo "'<option value={$row['id']}>{$row['value']}</option>'";
}

Categories