Reputation: 1042
I am currently populating a table with rows from a database. One of the columns is a dropdown that needs to be populated with multiple values.
Each dropdown is automatically defaulting to Bowling Green even if that row should not be Bowling Green. Most rows are either Southeast or Michigan but regardless of what it should be, it is defaulting to Bowling Green for some reason.
How can I have the dropdowns keep all values as options in the dropdown (bowling green, michigan, southeast), but have the dropdown value default to the value that it is in the database?
<?php
$sql = "SELECT TOP 100 *
FROM Table_OS_List
ORDER BY [CURRENT_SKU] ASC";
$drops = "SELECT [Purchasing_Group]
FROM Table_OS_List
GROUP BY [Purchasing_Group]";
$drop = $dbh->query($drops);
$allDrops = $drop->fetchAll();
?>
<?php
/* Foreach loop that brings in information to populate table */
foreach ($dbh->query($sql) as $rows) {
?>
<tr class="row">
<td class="old_sku" id="old_sku"><?php echo intval ($rows['OLD_SKU'])?></td>
<td class="current_sku" id="current_sku"><?php echo intval ($rows['CURRENT_SKU'])?></td>
<td class="id" id="id" style="display: none;"><?php echo intval ($rows['ID'])?></td>
<td class="dropdown-select" id="purchgroup">
<select id="selected_group" class="selected_group" disabled>
<?php
foreach($allDrops as $dropdown) { ?>
<option class="choice"
value="<?php echo $dropdown['Purchasing_Group'];?>">
<?php echo $dropdown['Purchasing_Group'];?>
</option>
<?php } ?>
</select>
</td>
<td><input type="button" class="edit" name="edit" value="Edit"></td>
<td><input type="button" class="delete" name="delete" id="<?php echo intval ($rows['ID'])?>" value="Delete"></td>
</tr>
<?php } ?>
Example of what it looks like now. You can see that it has multiple options which is what I need, but, regardless of it's value in the database, is defaulting to Bowling Green:
Upvotes: 0
Views: 31
Reputation: 114
You can add a selected
attribute with a inline ternary operator just like so;
<option class="choice" <?php echo $dropdown['Purchasing_Group'] ? ' selected' : null ?> value="<?php echo $dropdown['Purchasing_Group'];?>">
<?php echo $dropdown['Purchasing_Group'];?>
</option>
and after you fetching all the datas from the DB, always good to check if result or results existing.
Upvotes: 0
Reputation: 8621
You need to add the selected
attribute to the correct option.
Something like this:
<option class="choice"
<?php echo $row['Purchasing_Group'] == $dropdown['Purchasing_Group'] ? "selected" : ""; ?>
value="<?php echo $dropdown['Purchasing_Group'];?>">
<?php echo $dropdown['Purchasing_Group'];?>
</option>
Where $row['Purchasing_Group']
is the column in the Table_OS_List
table.
The important code here is <?php echo $row['Purchasing_Group'] == $dropdown['Purchasing_Group'] ? "selected" : ""; ?>
- this is known as a Ternary
, it could also be written in expanded form like this:
<?php
if($row['Purchasing_Group'] == $dropdown['Purchasing_Group']) {
echo "selected";
}
?>
Upvotes: 2