Issue
Right now I have a working solution for populating an HTML <select>
/<option>
-dropdown with the content through PHP/MYSQLI from my database: listoption
.
The database:
DATABASE NAME:
# listoption
TABLES:
# ID INT(11) *Primary AI
# listoption_item VARCHAR(255)
Here's the other code (not the mysqli connect but everything afterwards..)
<?php
$result = $mysqli->query("select * from listoption");
echo "<select id='list' name='list'>";
while ($row = $result->fetch_assoc()) {
$listoption_item = $row['listoption_item'];
echo '<option value="'.$listoption_item.'">'.$listoption_item.'</option>';
}
echo "</select>";
?>
But the problem is now that I want to have one of these options that are populated through that query to be selected
. And the option to be selected should be determed by a parameter in the URL, for example: index.php?id=1
.
So now I need to somehow add a IF/ELSE and a $_GET['id'];
into the code to make it identify if the ID from the database is the same as the populated item and then set it to selected.
Any idéas? Thanks!
Solution
You can do that like given below:
<?php
$result = $mysqli->query("select * from listoption");
$id = ($_GET['id'])? $_GET['id'] : '';
echo "<select id='list' name='list'>";
while ($row = $result->fetch_assoc()) {
$listoption_item = $row['listoption_item'];
$sel = ($id == $row['id'])? 'selected="selected"':'';
echo '<option value="'.$listoption_item.'" '.$sel.'>'.$listoption_item.'</option>'; // $sel will deside when to set `selected`
}
echo "</select>";
?>
Answered By - Himanshu Upadhyay
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.