Forum Moderators: coopster
I'm pulling names from a database into a select box using a while loop. The output looks like $last_name, $first_name. But even though there are no empty rows in the table, the first option in the select box is just the comma. So the first result is returning blank. I'd rather the first name appear rather than just a plain comma or character.
This might be easy to understand but I don't see why this code (in blue) below works, the original code that causes the problem comes first:
// Original
if ($num < 1) {
$display_block = "<p><em>Sorry! No results.</em></p>";
} else {
while ($row = mysql_fetch_array($result)) {
$id = $row['id'];
$fname = $row['fname'];
$lname = $row['lname'];
$option_block .= "<option value=\"$id\">$fname, $lname</option>";
}
// Here is the form to be displayed
$display_block = "
<form method=\"post\" action=\"modify.php\">
<p><strong>Contact:</strong></p>
<select name=\"id\">
$option_block
</select>
<input type=\"submit\" name=\"submit\" value=\"Select this Contact\" /></p>
</form>";
}
// Fixed
// This code puts the first name in the select box (in place of the comma) as it should:
} else {
while ($row = mysql_fetch_array($result)) {
$id = $row['id'];
$fname = $row['fname'];
$lname = $row['lname'];
if ($fname == "") {
$option_block = "";
} else {
$option_block .= "<option value=\"$id\">$fname, $lname</option>";
}
}
Now, the part that's confusing is, this also works:
} else {
while ($row = mysql_fetch_array($result)) {
$id = $row['id'];
$fname = $row['fname'];
$lname = $row['lname'];
if ($fname == "") {
} else {
$option_block .= "<option value=\"$id\">$fname, $lname</option>";
}
}
I know that can't be correct, what's going on here?
Thanks for any help
1. if fname is empty concatenate nothing to the string else concatenate the option element
2. if fname is empty do nothing else concatenate the option element
it would be better like this
if ($fname!= "") {
$option_block .= "<option value=\"$id\">$fname, $lname</option>";
}
which is, if fname is not blank concatenate the option element.