将MySQL表回显到HTML表,显示空字段的文本
问题描述:
I am echoing a MySQL table to HTML table, but some of my database fields are empty. When a database field is empty, how can I specify an alternate text (rather than it just showing blank?
The following works perfect (with blank cells):
<?php
include("../config.php");
$link = mysqli_connect("$db_host" , "$db_user" , "$db_password" , "$db");
mysqli_select_db($link, $db);
$result = mysqli_query($link,"SELECT * FROM the_table");
echo "<table border='1'>
<tr>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['email'] . "</td>";
echo "<td>" . $row['phone'] . "</td>";
echo "</tr>";
}
echo "</table>";
?>
I think the answer should look something like this (but it doesn't work):
if (empty($row['name'])) {
echo "<td>Not Specified</td>";
} else {
echo "<td>" . $row['name'] . "</td>";
}
Suggestions?
答
I think this should work:
if ($row['name'] == null) {
echo "<td>Not Specified</td>";
} else {
echo "<td>" . $row['name'] . "</td>";
}
答
Try:
if(empty($row['name']) || $row['name'] == "")
See http://php.net/manual/en/function.empty.php for the empty documentation. Maybe your result contains spaces? Then use the trim function as commented on your question.