0

i have a query in PHP, i don't want to display broken images if the image data is not available in database

$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>

Please help me out! Thanks

Anshureddy
  • 15
  • 6

3 Answers3

3

You can use onerror attribute .

<img src="<?php echo $row["Photo"]; ?>" width="75" height="50" onerror="this.style.display='none';" />
Ashraf
  • 2,612
  • 1
  • 20
  • 35
0

Use The Following Code:

<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>
Nagaraja K
  • 46
  • 3
-1

Welcome to Stackoverflow, please try this code. (Assuming my understanding of your problem is correct).

$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>

I have improved couple of things, please check them:

  1. Instead of using <?php echo $var; ?>, please use <?= $var; ?>
  2. Also, try to avoid <? if() { and <? } ?>, try to use <? if (): and <? endif; ?>. It will make the code a lot more easier to read.
  3. Also, you can use HTML onerror attribute. This will execute JS on fallback if the image is not found at src.

References:

Aayush Sinha
  • 377
  • 4
  • 18