I have a number of dropdown lists, which update a database, however once updated the first object on the list is displayed, rather than the actual object selected. What is the best way to fix this?
Code sample: HTML code sample
<select name="sleeps">
<option value="0">Sleeps</option>
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
<option value='4'>4</option>
</select>
This is generated using:
<?php
for ($x = 1; $x <=10; $x++) {
echo "<option value='$x'>$x</option>";
}
?>
Desired result
<select name="sleeps">
<option value="0">Sleeps</option>
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
<option value='4' selected>4</option>
</select>
Figured it out :)
Note - $echo and $title are there to allow changes in order to allow flexibility.
function select_dropdown($sql, $echo, $title) {
include 'connect.php';
$id = $_GET['id'];
$select = $conn->prepare($sql);
$select->bind_param('s', $id);
$select->execute();
$select->store_result();
if ($select->num_rows > 0) {
$meta = $select->result_metadata();
echo "<select name='$title'>
<option value='0'>$title</option>\n";
while ($field = $meta->fetch_field()) {
$params[] = &$row[$field->name];
}
call_user_func_array(array($select, 'bind_result'), $params);
while ($select->fetch()) {
for ($x = 1; $x <=10; $x++) {
if ($row[$echo] == $x) {
echo "<option value='$row[$echo]' selected>$row[$echo]</option>";
} else {
echo "<option value='$x'>$x</option>";
}
}
}
$select->close();
echo "</select>";
}
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments