Reputation: 39
I am trying to display some data on that I successfully extracted from an SQL database. I have two bits of data, people's name and people's nickname.
If the person has a nickname, I want to display it in the data instead of the name. If they have no nickname I want to display the name. I tried using this bit of code but it effects all of the rows, rather than just those where the nickname field isn't empty.
Cam anybody offer some advice? Thanks in advance.
foreach ($rows as $row)
{
$name = $row["name"];
$nickname = $row["nickname"];
if($row["nickname"] !== NULL)
{
$name = $nickname;
}
echo "<tr>";
echo "<td> $name </td>";
echo"</tr>";
Upvotes: 0
Views: 2525
Reputation: 44581
You can use a shorten if
form to choose the variable to display and then concatenate it with your html
portions :
foreach ($rows as $row){
$html = "<tr>";
$html .= "<td> " . (empty($row["nickname"]) ? $row["name"] : $row["nickname"] ) . " </td>";
$html .= "</tr>";
echo $html;
}
Also you should echo
valid html
to display it correctly (as some <tag>
s require the closing </tag>
your html
won't be valid, so at first you can concatenate everything in one row and then echo
it ).
Upvotes: 1