Home > Software engineering >  How to display the book title, instead of cover image when cover image is missing
How to display the book title, instead of cover image when cover image is missing

Time:07-22

I'm working on a PHP/SQL project that is a library of Dr.Seuss books. I'm wondering how to display just the book title (instead of a broken image link) when the book does not have an image.

Here is the code I have right now for displaying just the Cover image of the book.

<section >
  <?php foreach ($books as $book) : ?>
        <a  href="book.php?id=<?php echo $book['book_id']; ?>"> <img  src="book-covers/<?php echo $book['book_image'];?>"></a>
  <?php endforeach; ?>
</section>

CodePudding user response:

Since you are using the alternative PHP syntax (sometimes called the template format), you might appreciate the conditional in that format, too.

The following code checks for the image, and if set renders as you had it, otherwise it renders a link with some text, I’ll let you fill in the blank for the database/array.

This version is more verbose than a ternary, but there’s a good chance you’ll need a different CSS class, too (shown in the example), so I broke it out that way.

<section >
  <?php foreach ($books as $book) : ?>
      <?php if($book['book_image']): ?>
        <a  href="book.php?id=<?php echo $book['book_id']; ?>"> <img  src="book-covers/<?php echo $book['book_image'];?>"></a>
      <?php else: ?>
        <a  href="book.php?id=<?php echo $book['book_id']; ?>">Book text here</a>
      <?php endif; ?>
  <?php endforeach; ?>
</section>

CodePudding user response:

Chris Haas' answer is very accurate (verbose, CSS). If however you want to use, or better understand, the ternary expression, you can try as follows:

Book array data:

<?php
$books = array(
"Book 1" =>
array (
    "book_id"=> "1",
    "book_title"=> "title 1",
    "book_image"=> "image 1"),
"Book 2" =>
array (
    "book_id" => "2",
    "book_title" => "title 2",
    "book_image" => "",)
);
?>

Your code:

<section >
<?php foreach ($books as $book) : ?>
    <a  href="book.php?id=<?php echo $book['book_id']; ?>">
        <?php
        //echo ($some_condition) ? 'The condition is true!' : 'The condition is false.';
        echo ($book['book_image']) ? '<img  src="book-covers/'.$book["book_image"].'">' : '<span >'.$book["book_title"].'</span>';
        ?>
    </a>
<?php endforeach; ?>
</section>

Sandbox links https://onlinephp.io/c/16012

  • Related