So I have this table
from my database
that I want to echo out
using select
option
. But I'm having trouble because I have an option
where the user can add more options and I don't know how to set the value of it. Can you help me about it guys? thanks!
Here is my current code:
<?php
while(mysqli_stmt_fetch($stmt)) {
?>
<select class="form-control input-sm">
<option value="ABLE SEAMAN" <?php if($boiler_size == 'ABLE SEAMAN') { echo "selected"; } ?>>ABLE SEAMAN</option>
<option value="AKO ITO" <?php if($boiler_size == 'AKO ITO') { echo "selected"; } ?>>AKO ITO</option>
<option value="APPRENTICE" <?php if($boiler_size == 'APPRENTICE') { echo "selected"; } ?>>APPRENTICE</option>
</select>
Simply write function :
function populate_options($table_name, array $fields, $selected_option = "") {
$options = "<option></option>";
$st = $pdo->prepare("SELECT distinct `$fields[0]`, `$fields[1]` FROM $table_name WHERE 1 GROUP BY `$fields[1]` ");
$st->execute();
$rowes = $st->fetchAll(PDO::FETCH_ASSOC);
if ($selected_option=="") {
foreach ($rowes as $row) {
$options.= "<option value = '{$row->$fields[0]}'";
$options.= ">" . ucwords( $row->$fields[1] ) . "</option>";
}
} else {
foreach ($rowes as $row) {
$options.= "<option value = '{$row->$fields[0]}'";
$options.= ((($selected_option == $row->$fields[0])) ? ' selected="selected"' : '') . ">" . ucwords($row->$fields[1] ). "</option>";
}
}
}
return $options;
}
and call in your code
<select class="form-control input-sm">
<?php echo $populate_options("tbl_name", array('id', 'name'),$boiler_size); ?>
</select>
You have to get the count of the rows that has been selected from the DB since if the count is Zero it will be throwing error in the while loop
or foreach
as preferred usage for the showing up the dynamic select options.
Hence for showing up of the dynamic select options we need to do the following process.
<?php
$query="SELECT * FROM `TABLENAME` ORDER BY `id` DESC";
$stmt = mysqli_query($conn,$query);
$count = $stmt->num_rows;
?>
<select class="form-control input-sm">
<?php
if($count==0)
{
echo '<option value="">No Datas have been created Yet</option>';
}
else
{
while($fetch = $stmt->fetch_assoc())
{
?>
<option value="<?php echo $fetch['id']; ?>"><?php echo $fetch['name']; ?></option>
<?php
}
}
?>
</select>
Bu using the above codes you can fetch n-numbers of the option values from the DB and you can display it very easy without any confusions. The option value will be repeating till the loop ends and after that alone the select
will end . So if the DB has n-number
the while loop will repeat for n-number of times and will end up after that.