如果在数据库中没有可用的图像,则隐藏损坏的图像

时间:2018-10-09 05:48:49

标签: php mysql

我在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>

请帮帮我! 谢谢

3 个答案:

答案 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>

我已经改善了几件事,请检查一下:

  1. 请使用<?php echo $var; ?>而不是使用<?= $var; ?>
  2. 此外,请尝试避免使用<? if() {<? } ?>,并尝试使用<? if ():<? endif; ?>。它将使代码更易于阅读。
  3. 此外,您可以使用HTML onerror属性。如果在src中找不到该图片,则会在后备时执行JS。

参考文献: