PHP MySQL Drop Down Box Populate Selected Value - php

I have read tutorials about how to populate an entire Drop down list with MySQL, but the problem I am running into is that I only want to grab the one from the database and have that be the selected one. So I would have like a drop down with three items (Item1, Item2, Item3) in the database its stored in a column called itemschoice which has a value of 'Item2'. How do I go about getting item2 to be selected when I load the drop down box?

In your <option> element add the selected attribute for the value that is in itemschoice.
Crude example using a made up function to get the choice:
$choice = get_items_choice();
$results = mysqli_query($sql);
echo '<select name="whatever">';
while($row = mysqli_fetch_array($results)) {
if ($row['choice'] === $choice) {
echo '<option value="' . $choice . '" selected="selected" />';
} else {
echo '<option value="' . $choice . '" />';
}
}
echo '</select>';
This is just an example, don't copy & paste this without adding some kind of error verification!

Related

Select Option inside value with php

I have a trouble about select option value choosing with PHP
Multiple select box is showing for state and city. Jquery loads as ajax method for database. And I need to reach "option value" inside value. I will show the problem inside below codes.
<?php
function load_country() {
include 'includes/db.php';
$sql = "SELECT * FROM ilce ORDER BY name";
mysqli_set_charset($con, "UTF8");
$result = mysqli_query($con, $sql);
while($row = mysqli_fetch_array($result)) {
$output .= '<option name="' . $row['name'] .'" value="' .
$row["ilce_id"].'">' . $row["name"]. '</option>';
}
return $output;
}
?>
<select class="form-control" name="state" id="state">
<option>Choose State</option>
<?php
echo load_country();
?>
</select>
<?php
$state = mysqli_real_escape_string($con, $_POST['state']);
echo $state;
?>
<option value="5">New York</option>
$state is showing for me Example : "id" => 5
Thus, I want to reach "New York", inside value.
Please help me
Thanks
The text content of an <option> element is not posted to the server, only its value.
If you're inserting the selected state into a database (like in a user table), you might just insert the numeric state ID and join the two tables when you need to display the information.
Alternatively, you can fetch an array of all states indexed by their IDs and then reference that array:
while ($row = mysqli_fetch_array($result)) {
$allStates[$row['ilce_id']] = $row['name'];
}
$stateId = $_POST['state'];
$thisState = $allStates[$stateId];
echo $thisState;
Or just fetch the one row that you need by its ID, depending on what you need.
A less desirable solution is to set the <option> value to the row's name rather than its ID:
$output .= '<option value="' . $row["name"] . '">' . $row["name"] . '</option>';
But that seems to defeat the purpose of using a relational database.
Also see Get Text From Tag Using PHP.

How can I use the results of my query in a dropdown menu?

I am trying to create a dropdown menu that will have as options certain fields recovered from a database using a for loop.
I am doing the following:
for ($article_id=1; $article_id <=30; $article_id++)
{
$sqltitles = "SELECT title FROM articles WHERE article_id='$article_id'";
$cursor = mysqli_query($db, $sqltitles) or die($sqltitles."<br/><br/>".mysql_error());
$row = mysqli_fetch_row($cursor);
$titles = $row[0];
echo $titles;
echo "</br>";
}
Which draws all the titles from the database and shows them one at a time.
Is there any way to make all those titles appear as options to a dropdown menu, so the user can select which one to read?
Something like this should work. I made a modification to how the query is working. If you specify article IDs for a range of articles in your query rather than just one specific ID, you should be able to execute only one query instead of one for each ID you want to retrieve. Regardless of whether or not you decide to use the approach I suggested, the syntax for creating the dropdown menu should be the same.
<select>
<?php
$sqltitles = "SELECT title FROM articles WHERE article_id BETWEEN 1 AND 30" ;
$cursor = mysqli_query($db, $sqltitles) or die($sqltitles."<br/><br/>".mysql_error());
while ($row = mysqli_fetch_row($cursor)) {
echo '<option value ="' . $row[0] . '">' . $row[0] . '</option>';
}
?>
</select>
Here is a good reference for how to create HTML <select> tags.
try something along the lines of...
echo '<select name="dropdownname">';
foreach ($titles as $key => $val) {
echo('<option value="' . $val .'">' . $val . '</option>');
}
echo '</select>';

Getting value from populated drop down list

I have populated a drop down list from the database but i dont think the value is being set to the name the user chooses from the drop down as when the form is selected, no value is added to the database.
At the moment, it shows all the names from that table. As i said, i want the value to be the name the user chooses so that when the form is submitted it is added to the database and can be fetched on another page.
<select name="category">
<?php
$sql = mysql_query("SELECT category_Name FROM category");
while ($row = mysql_fetch_array($sql)){
echo '<option value="'.$category_Name.'">' . $row['category_Name'] . "</option>";
}
?>
echo '<option value="'.$category_Name.'">' . $row['category_Name'] . "</option>";
// ^ this var is never set
should be
echo '<option value="'.$row['category_Name'].'">' . $row['category_Name'] . "</option>";
// ^ change this
or you can just have it like this
echo '<option>' . $row['category_Name'] . "</option>";
If value is not set, it just takes the value of the display name.

PHP Dropdown of all records from database + select current set record

I have a PHP dropdown of a list of groupnames (together with id, so it can be updated). In this FORM page you can change the groupname specified for an item by choosing possibilities from the dropdown coming out from the database. My code below works, but there must be a better way, because I get the first field as the currently set, and then all the possibilities, so I get this record twice.
Example:
- Keyboard (Currently set)
- Speakers (Possible to choose, straight from DBS)
- Midi Controllers (Possible to choose, straight from DBS)
- Keyboard (Possible to choose, straight from DBS)
- Drum set (Possible to choose, straight from DBS)
As you see I get the currently set record again.
My code:
echo "<select name='itemgroupid'>";
// CHOOSE CURRENT SET RECORD AS SELECTED ITEM
echo "<option value='" . $itemgroupid . "'>";
$selected="
SELECT item.itemid, itemgroup.itemgroupname, itemgroup.itemgroupid
FROM item, itemgroup
WHERE item.itemid=$itemid";
$selectedresult=mysql_query($query) or die("query fout " . mysql_error() );
while($record=mysql_fetch_array($selectedresult) ) {
echo "" . $itemgroupname . "</option>";
}
// QUERY TO SHOW ALL POSSIBLE CHOOSABLE RECORDS FROM DATABASE
$itemgroupquery="SELECT itemgroupname,itemgroupid FROM itemgroup";
$itemgroupqueryresult = mysql_query ($itemgroupquery);
while($nt=mysql_fetch_array($itemgroupqueryresult)){
echo "<option value=$nt[itemgroupid]>$nt[itemgroupname]</option>";
}
echo "</select>";
There are 2 ways to achieve what you're looking for:
1) To show the selected item at the top of the dropdown
echo "<select name='itemgroupid'>";
// CHOOSE CURRENT SET RECORD AS SELECTED ITEM
echo "<option value='" . $itemgroupid . "'>";
$selected="
SELECT item.itemid, itemgroup.itemgroupname, itemgroup.itemgroupid
FROM item, itemgroup
WHERE item.itemid=$itemid";
$selectedresult=mysql_query($query) or die("query fout " . mysql_error() );
while($record=mysql_fetch_array($selectedresult) ) {
echo "" . $itemgroupname . "</option>";
}
// QUERY TO SHOW ALL POSSIBLE CHOOSABLE RECORDS FROM DATABASE
$itemgroupquery="SELECT itemgroupname,itemgroupid FROM itemgroup WHERE item.itemid != $itemid";
$itemgroupqueryresult = mysql_query ($itemgroupquery);
while($nt=mysql_fetch_array($itemgroupqueryresult)){
echo "<option value=$nt[itemgroupid]>$nt[itemgroupname]</option>";
}
echo "</select>";
2) Show the selected item in it natural place
echo "<select name='itemgroupid'>";
// QUERY TO SHOW ALL POSSIBLE CHOOSABLE RECORDS FROM DATABASE
$itemgroupquery="SELECT itemgroupname,itemgroupid FROM itemgroup";
$itemgroupqueryresult = mysql_query ($itemgroupquery);
while($nt=mysql_fetch_array($itemgroupqueryresult)){
echo "<option value=$nt[itemgroupid]";
if( $itemid == $nt['itemgroupid'] ) echo ' selected="selected"';
echo ">$nt[itemgroupname]</option>";
}
echo "</select>";
HTH
OK
In your code.
rather than output your selected value at the top, do it the proper way :)
Select your current item (make a note of the itemgroupid for example)
then in your output
while($nt=mysql_fetch_array($itemgroupqueryresult)){
echo "<option ";
if ($savedid==$nt[itemgroupid]) echo "selected ";
echo "$nt[itemgroupid]>$nt[itemgroupname]</option>";
}
echo "</select>";
This will produce with $savedid=1
<option value=0>group 0</option>
<option selected value=1>group 1</option>
<option value=2>group 2</option>
Add the default selected record to a empty array first like
toDisplay = array('selected_record');
Then, get the data from the database using your sql and append it to this array.
Later run a array_unique on it and finally using a loop create the html output string, in the same way you are doing it now.

How to generate a state/province dropdown that selects the value in the database

So I have several places for country and state/province dropdowns. What I'd like to do is have a function for each of these and when I run my while loop on customer data from mysql I want to select the right by default from the data in the database.
Reason is right now the dropdowns default to the HTML selected one so if users don't change it to theirs again when they edit their account they re-save their info with the wrong state/country.
I'd also like to use this in several places so I want a big array of countries and states/provinces that loop.
Just looking for a hand or be pointed to where this has been done in a function already.
Thank you kindly.
$states - query with all states, $user_state - current user's state. So your user's choice will be selected by default.
<?php
echo '<select name="state">';
while ($state = mysql_fetch_assoc($states))
{
echo '<option value="' . $state['state'] . '"';
if ($user_state == $state['state'])
{
echo ' selected';
}
echo '>' . $state . '</option>';
}
echo '</select>';

Categories