How do I echo selected select option if equal to ID?

Below is what I tried:

$intID = ‘1’;
$sql = “…”;
$result = mysqli_query($con, $sql);

echo “”;
while($row = mysqli_fetch_array($result)) {
echo “<option value=”" . $row[‘pkID’] . “”" . $intID == $row[‘pkID’] ? " selected=“selected”" : “” . “/>” . $row[‘Name’] . “”;
}
echo “”;

First I like working with ’ instead of " for you don’t have to do ", and with that said I think you are looking for something like the following?

[php]<?php
$intID = ‘1’;
$sql = “…”;
$result = mysqli_query($con, $sql);

echo ‘’;
while($row = mysqli_fetch_array($result)) {
echo ($intID == $row[‘pkID’]) ? ‘’ . $row[‘Name’] . ‘’ : ‘’ . $row[‘Name’] . ‘’;
}
echo “”;[/php]

You could have also broken the option statement down and used the ternary (or if statement) statement that way, but in my opinion that gets a little messy. This way you can just look at it and see the logic without any commenting.
I’m also assuming there is more mysqli code for even though it’s been a while since I use mysqli (I use PDO) I’m pretty sure this won’t work as it is.

Sponsor our Newsletter | Privacy Policy | Terms of Service