Populating Dropdown HTML Menu with MySQL Query Results - php

I'm attempting to populate an HTML dropdown menu with the results of a MySQL query. The query is running fine and not throwing any errors, but for some odd reason the results won't display correctly.
<?php
$query = "SELECT * FROM parts WHERE itemName LIKE 'Processors:%'";
$result = mysql_query($query) or die("Unable to query CPU parts");
while($row=mysql_fetch_array($result)) {
$option .= "<option value='{$row['itemName']}'></option>";
}
?>
<select name="cpu"><? echo $option; ?></select>
I'm pretty sure it lies somewhere in the $option .= ... ; but it I can't seem to figure it out.

You are not printing the value to be shown in dropdown
try this
while($row=mysql_fetch_array($result)) {
$option .= "<option value='{$row['itemName']}'>{$row['itemName']}</option>";
}
I saw that you are using short tags here
<select name="cpu"><? echo $option; ?></select>
please make sure you have short tag enabled in php.ini

Two things:
You need to initialize $option and print the value to be shown in the dropdown
<?php
$query = "SELECT * FROM parts WHERE itemName LIKE 'Processors:%'";
$result = mysql_query($query) or die("Unable to query CPU parts");
$option = "";
while($row=mysql_fetch_array($result)) {
$option .= "<option value='{$row['itemName']}'>{$row['itemName']}</option>";
}
?>
<select name="cpu"><? echo $option; ?></select>

Seems you forget to add a value inside <option></option> field you only set value for fetching $_POST[] but not for viewing. :D
Also seeing $option variable to be concatenated seems that you already declared it at first
if not you need to probably declared it first.cause this may result to error undefined variable.
<?php
$query = "SELECT * FROM parts WHERE itemName LIKE 'Processors:%'";
$result = mysql_query($query) or die("Unable to query CPU parts");
$option = '';
while($row=mysql_fetch_array($result)) {
$option .= '<option value='.$row['itemName'].'>'. $row['itemName'].'</option>';
}
?>
<select name="cpu"><?php echo $option; ?></select>

Forgot the simplest part:
$aa .= "{$row['itemName']}";
I needed to add the actual label to be displayed between the option tags :)

Related

Adding a variable value as an option in a PHP echo created drop down menu

I am using a PHP script within an HTML page to create a dropdown menu with results populated from a database. I am using the PHP script in the HTML page because I'd like the dropdown menu to remain on the same page as a number of options.
When creating an option in the dropdown menu via an echo, it won't allow me to use the value of a variable (i.e. the value of a field in the database that has been retrieved) in the option tag. Here is the code:
<select name="comics">
<OPTION>Select an option</OPTION>;
<?php
include_once('includes/conn.inc.php');
$query = ("SELECT comicID, comicName FROM comic");
$result = mysqli_query($conn, $query);
while ($row = $result->fetch_assoc())
{
echo "<option> .$row['comicName']. </option>";
}
?>
</select>
As is, the code creates the drop down menu and adds the "Select an option" line. The second option is created, but the value reads as " .$row['comicName']. " instead of, for example, "Superman".
Thanks in advance.
Have you named the file with a php extension ? try doing a print_r with $result before the while loop
Your solution tries performing concatenation without closing the double-quotes first, so it treats the variable as a string. Try this:
echo "<option>" . $row['comicName'] . "</option>";
Try:
<select name="comics">
<OPTION>Select an option</OPTION>;
<?php
include_once('includes/conn.inc.php');
$query = ("SELECT comicID, comicName FROM comic");
$result = mysqli_query($conn, $query);
while ($row = $result->fetch_assoc())
{
echo "<option value='".$row['comicName']."'>".$row['comicName']."</option>";
}
?>
</select>
Let me know if works.

PHP echo out data into HTML drop drop down menu

I have a HTML etc.. tags now what I want to achieve is upon a selection of ie. i want to load the related info from database to in a new tag with as many tags.
I am using PHP to do achieve this now at this point if for example i choose option1 then the query behind it retrieves relevant information and stores it in a array, and if I select option2 exactly the same is done.
The next step I made is to create a loop to display the results from array() but I am struggling to come up with the right solution to echo retrieved data into etc. As its not my strongest side.
Hope you understand what I am trying to achieve the below code will clear thing out.
HTML:
<select id="workshop" name="workshop" onchange="return test();">
<option value="">Please select a Workshop</option>
<option value="Forex">Forex</option>
<option value="BinaryOptions">Binary Options</option>
</select>
PHP:
$form = Array();
if(isset($_POST['workshop'])){
$form['workshop'] = $_POST['workshop'];
$form['forex'] = $_POST['Forex'];
$form['binary'] = $_POST['Binary'];
//Retrieve Binary Workshops
if($form['workshop'] == 'Forex'){
$sql2 = "SELECT id, course, location FROM courses WHERE course LIKE '%Forex%' OR course LIKE '&forex%'";
$query2 = mysqli_query($link, $sql2);
while($result2 = mysqli_fetch_assoc($query2)){
//The problem I am having is here :/
echo "<select id='Forex' name='Forex' style='display: none'>";
echo "<option value='oko'>.$result[1].</option>";
echo "</select>";
print_r($result2);echo '</br>';
}
}else{
$sql = "SELECT id, course, location FROM courses WHERE course LIKE '%Binary%' OR course LIKE '%binary%'";
$query = mysqli_query($link, $sql);
while($result = mysqli_fetch_assoc($query)){
print_r($result);echo '</br>';
}
}
}
Try this code:
$query2 = mysqli_query($link, $sql2);
echo "<select id='Forex' name='Forex' style='display: none'>";
while($result2 = mysqli_fetch_assoc($query2)){
echo "<option value='oko'>{$result['course']}</option>";
}
echo "</select>";
echo '</br>';
From the top in your php:
// not seeing uses of the $form I removed it from my answer
if(isset($_POST['workshop'])){
$workshop = $_POST['workshop'];
$lowerWorkshop = strtolower($workshop);
// neither of $_POST['Forex'] nor $_POST['Binary'] are defined in your POST. you could as well remove those lines?
//Retrieve Binary Workshops HERE we can define the sql in a single line:
$sql = "SELECT id, course, location FROM courses WHERE course LIKE '%$workshop%' OR course LIKE '&$lowerWorkhop%'";
$query = mysqli_query($link, $sql); // here no need to have two results
// Here lets build our select first, we'll echo it later.
$select = '<select id="$workshop" name="$workshop" style="display: none">';
while($result = mysqli_fetch_assoc($query)){
$select.= '<option value="' . $result['id'] . '">' . $result['course'] . '</option>';
// here I replaced the outer containing quotes around the html by single quotes.
// since you use _fetch_assoc the resulting array will have stroing keys.
// to retrieve them, you have to use quotes around the key, hence the change
}
$select.= '</select>';
}
echo $vSelect;
this will output a select containing one option for each row returned by either of the queries. by the way this particular exemple won't echo anything on screen (since your select display's set to none). but see the source code to retrieve the exemple.

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>'";
}

Dynamic PHP Dropdown Menu for Countries

Okay so I have a table called Countries and it looks like this:
---------------------------
|Country | Code |
---------------------------
|Afganastan | AF |
|Ă…LAND ISLANDS| AX |
| etc. | etc. |
---------------------------
The thing that I want to do is create a dynamic menu in which the user chooses a country and that itself gets stored as a value that I can call after the user hits submit.
I did try something here but I'm not sure what its doing because I am still new to PHP and HTML to the point where I just type things in to see what would happen.
Anyways I am really stuck and I tried using google and the search feature in this site and nothing I found worked for me...
The code I tried is this:
<select>
<?php
$result = mysql_query('SELECT Country FROM Countries');
echo '<select name="country">';
while ($row = mysql_fetch_array($result))
{
echo '<option value="'.$row['id'].'">'.$row['name'].'</option>';
}
echo '</select>';
?>
</select>
The result is supposed to look like a dropdown menu with the list of countries from the database in it. But this doesn't work and just shows this in the drop down:
.$row['name']
Which is nothing close to what I want because that's not even a country. when I remove that part of the code, then there is no option for the user to choose, the menu is empty.
EDIT
My code so far that still doesn't work:
<select name = 'country'>
<?php
include ("account.php");
include ("connect.php");
$result = mysql_query('SELECT Code , Country FROM Countries');
while ($row = mysql_fetch_array($result))
{?>
<option value="<?php echo $row['Code']?>"><?php echo $row['Country']?></option>
<?php}
?>
</select>
The include ("account.php"); and include ("connect.php"); lines allow me to connect to my database.
you code should be something like this
$host = "localhost";
$user = "root";
$pass = "yourpassword";
$db = "databasename";
// This part sets up the connection to the
// database (so you don't need to reopen the connection
// again on the same page).
$ms = #mysql_connect($host, $user, $pass);
if ( !$ms )
{
echo "Error connecting to database.\n";
}
// Then you need to make sure the database you want
// is selected.
#mysql_select_db($db);
<form method = "POST" action = "abc.php">
<select name = 'country'>
<?php
$result = mysql_query('SELECT id , name FROM Countries');
while ($row = mysql_fetch_array($result))
{?>
<option value="<?php echo $row['id']?>"><?php echo $row['name']?></option>
<?php}
?>
<input type = "submit" value = "Submit">
</form>
Now in php use this
echo '<pre>';
print_r($_POST);
And you will see what user selected. Check your settings there might be some problem.
Your single and double quotes are messing you up:
echo '<option value="'.$row['id'].'">'.$row['name'].'</option>';
should be:
echo "<option value=\"" . $row['id'] . "\">" . $row['name'] . "</option>";
You can use a single quote around your script but when you jump out of it to do the $row['id'] and $row['name'] you are running into issues because it thinks you are jumping back into your quoted code... Either use my example above, starting/ending with double-quotes and escaping all double-quotes inside that need to display, or escape your single quotes in the $row[\'id\'] and $row[\'name\']
Thant should help you out.
Try this code
<?php
$result = mysql_query('SELECT * FROM Countries');
?>
<select name="country">
<?php
while ($row = mysql_fetch_array($result))
{
?>
<option value="<?php echo $row['id']; ?>"><?php echo $row['name']; ?></option>
<?php
}
?>
</select>
Firstly your table doesn't have a column id. Try changing your query like
SELECT Country, Code FROM Countries
Then the code and the html should be like this
<?php
$host = "localhost";
$user = "user"; //username
$pass = "pass"; //password
$db = "db"; //database
$con = #mysql_connect($host, $user, $pass);
if ( !$con )
{
echo "Error connecting to database.\n";
}
#mysql_select_db($db);
?>
<select name="country">
<option value="0" selected="selected">Choose..</option>
<?php
//echo '<select name = \'country\'>';
$result = mysql_query('SELECT Country, Code FROM Countries');
while ($row = mysql_fetch_array($result))
{
echo '<option value="'.$row['Code'].'">'.$row['Country'].'</option>';
}
?>
</select>
<select>
<?php
$result = mysql_query('SELECT Country FROM Countries');
echo '<select name="country">';
$row = mysql_fetch_array($result)
for ($i=0; $i<count($row ); $i++)
{
echo '<option value="'.$row[$i]['id'].'">'.$row[$i]['name'].'</option>';
}
echo '</select>';
?>
next page use print_r($_POST);
or var_dump($_REQUEST);
If you are using mysql_fetch_array you can use either the field names or their selected index to read them from the fetched row. You can also use either the sprintf or printf functions to merge content into a string to help keep the HTML fragment clean of the quotes needed to merge in values otherwise.
$result = mysql_query('SELECT Country, Code FROM Countries');
while ($row = mysql_fetch_array($result)) {
printf('<option value="%1$s">%2$s</option>',
$row['Code'], $row['Country']);
}
Your SQL statement selected only 'Country' from the 'Countries' table; as a result, it's impossible for you to use $row['id'] and $row['name'].
Use this instead:
echo '<select name="country">';
while ($row = mysql_fetch_array($result))
{
echo '<option value="'.$row['Code'].'">'.$row['Country'].'</option>';
}
echo '</select>';
?>
That should solve your problem.
I figured out the problem I was having. The first being that there was an extra select tag in the page and the second that the file was saved as a html page instead of a php file. Thank you to everyone that helped me figure this out!
Try my code, I'm using this and it really works... just change the values...
<?php
include ('connect.php');
$sql = "SELECT * FROM casestatusfile";
$result = mysql_query($sql);
echo "<select name = 'txtCaseStatus'/>";
echo "<option value = ''>--- Select ---</option>";
$casestatus = $_POST['txtCaseStatus'];
$selected = 'selected = "selected" ';
while ($row = mysql_fetch_array($result)) {
echo "<option " .($row['CASESTATUSCODE'] == $casestatus? $selected:''). "value='". $row['CASESTATUSCODE'] ."'>" . $row['CASESTATUS'] ."</option>";
}
echo "</select>";
?>
I'm sure that is working because that is the one that i'm using....

Problem populating a dropdown box with MySQL query results (PHP/MySQL)

so as the title states, using the following code I have got it populating the dropbox with a single result from the query, that result being the latest added in the table.
here is my code:
<?php
$query = "SELECT * FROM units_tb WHERE user_id='$userid'";
$result = mysql_query($query) or die (mysql_error());
while($row = mysql_fetch_assoc($result)){
$aa = "<option value='{$row['unit_id']}'>{$row['unit_code']}</option>";
}
?>
<select name="t_unit"><? echo $aa; ?></select>
The odd thing is, I use this same code for another field, and it works, populating the dropdown with all the results, however in this case it only fills in the last unit code in the table and not all of which are attached to the particular user id.
I would appreciate anyones thoughts :D
thanks
$aa .= "<option value='{$row['unit_id']}'>{$row['unit_code']}</option>";
add . before = and initiate $aa = ''; before while loop
<?php
$query = "SELECT * FROM units_tb WHERE user_id='$userid'";
$result = mysql_query($query) or die (mysql_error());
$options = "";
while($row = mysql_fetch_assoc($result)){
$options .= "<option value='{$row['unit_id']}'>{$row['unit_code']}</option>";
}
?>
<select name="t_unit"><? echo $options; ?></select>
should work. You forgot a . in your while loop

Categories