我在PHP中有一个查询,如果图像数据在数据库中不可用,我不想显示损坏的图像
$sql = "SELECT * FROM Candidates c1 LEFT JOIN Parties p1 on p1.Id =
c1.CurrentParty where c1.Id = 1 ";
$result = $conn->query($sql);
<div class="candidates">
<h5>Candidates for 2019 Vice-President Elections</h5>
<table class="table-bordered table">
<tr>
<th>Candidate Name</th>
<th>Party Name</th>
<th>Party Symbol</th>
<th>Candidate Image</th>
</tr>
<?php
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
?>
<tr>
<td><?php echo $row["CandidateName"]; ?></td>
<td><?php echo $row["PartyName"]; ?></td>
<td><img src="<?php echo $row["PartySymbol"]; ?>" width="75" height="50" />
</td>
<td><img src="<?php echo $row["Photo"]; ?>" width="75" height="50" /></td>
</tr>
<?php }}?>
</table>
</div>
请帮帮我! 谢谢
答案 0 :(得分:1)
您可以使用onerror
属性。
<img src="<?php echo $row["Photo"]; ?>" width="75" height="50" onerror="this.style.display='none';" />
答案 1 :(得分:0)
使用以下代码:
<td><?php echo ($row["PartySymbol"] != "")? '<img src='.$row["PartySymbol"].' width="75" height="50" />' : ''; ?> </td>
<td><?php echo ($row["Photo"] != "")? '<img src='.$row["Photo"].' width="75" height="50" />' : ''; ?></td>
答案 2 :(得分:-1)
欢迎使用Stackoverflow,请尝试以下代码。 (假设我对您的问题的理解是正确的。)
$sql = "SELECT * FROM Candidates c1 LEFT JOIN Parties p1 on p1.Id =
c1.CurrentParty where c1.Id = 1 ";
$result = $conn->query($sql);
<div class="candidates">
<h5>Candidates for 2019 Vice-President Elections</h5>
<table class="table-bordered table">
<tr>
<th>Candidate Name</th>
<th>Party Name</th>
<th>Party Symbol</th>
<th>Candidate Image</th>
</tr>
<?php
if ($result->num_rows > 0) :
while ($row = $result->fetch_assoc()) :
?>
<tr>
<td><?= $row["CandidateName"]; ?></td>
<td><?= $row["PartyName"]; ?></td>
<td>
<img src="<?= $row["PartySymbol"]; ?>" width="75" height="50" />
</td>
<td>
<?php if($row["Photo"]): ?>
<img src="<?= $row["Photo"]; ?>" width="75" height="50" />
<?php endif; ?>
</td>
</tr>
<?php
endwhile;
endif;
?>
</table>
</div>
我已经改善了几件事,请检查一下:
<?php echo $var; ?>
而不是使用<?= $var; ?>
<? if() {
和<? } ?>
,并尝试使用<? if ():
和<? endif; ?>
。它将使代码更易于阅读。onerror
属性。如果在src中找不到该图片,则会在后备时执行JS。参考文献: