I have a problem where the <option selected>
showing twice.
I am populating the <select><option>
with data from titles table
I want to show selected option based on data from taos table.
The data output is shown as:
https://phpout.com/wp-content/uploads/2023/05/P7V4E.png
and
https://phpout.com/wp-content/uploads/2023/05/nBFPh.png
<?php
$title_sql = "SELECT * FROM titles";
echo "<select class='form-control' name='title_id'>";
if ($result = mysqli_query($conn, $title_sql)) {
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$dbselected = $tao['title_id'];
foreach ($row as $option) {
if ($dbselected == $option) {
?>
<option selected value='$row[id]'><?php echo $row['title']; ?></option>
<?php
} else {
}
}
echo "<option value='$row[id]'>$row[title]</option>";
}
mysqli_free_result($result);
}
echo "</select>"; ?>
<?php
$title_sql = "SELECT * FROM titles";
echo "<select class='form-control' name='title_id'>";
if ($result = mysqli_query($conn, $title_sql)) {
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$dbselected = $tao['title_id'];
foreach ($row as $option) {
if ($dbselected == $option) {
?>
<option selected value='$row[id]'>
<?php echo $row['title']; ?>
</option>
<?php
} else {
}
}
echo "<option value='$row[id]'>$row[title]</option>";
}
mysqli_free_result($result);
}
echo "</select>"; ?>
Any assistance would be appreciated.
4
Answers
Look no further
<select><option>
from database showing selected option if found in another table Select an optionIn the
foreach
section you leftelse
section empty, and show your all select values outside the conditiontry this
Your
if
statement is outputting theoption
withselected
when it is equal to the$dbselected
value. Then you are outputting the option (withoutselected
) unconditionally. Move the lastecho
into theelse {
portion of thatif
to prevent it from being output if you have already outputted withselected
Also, you do not want the
foreach ($row as $option) {
; as that is walking through the columns of the row, so the secondecho
will be repeated for each column.Also, be consistent. Either use
echo
or drop out of PHP; don’t do it one way and then the other.Try it this way:
I would actually use
printf()
instead of theif-else
:I edited your question to show you how better formatting makes it easier to find your problem. your third echo statement is being executed first, It is outside your else block and should be inside it