1

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 class="books">
  <?php foreach ($books as $book) : ?>
        <a class="book grow" href="book.php?id=<?php echo $book['book_id']; ?>"> <img class="book-image" src="book-covers/<?php echo $book['book_image'];?>"></a>
  <?php endforeach; ?>
</section>
Chris Haas
  • 53,986
  • 12
  • 141
  • 274
nateIRL
  • 11
  • 2
  • Use a [ternary expression](https://stackoverflow.com/questions/17981723/how-to-write-a-php-ternary-operator) (conditional on the book image value) to write the `img` element (or not if there is no book image). – jsejcksn Jul 22 '22 at 00:09
  • I knew it would be an ifelse or a ternary. I just wasn't sure on how to apply it in this example. I'm still very new to all of this. – nateIRL Jul 22 '22 at 00:17

2 Answers2

1

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 class="books">
  <?php foreach ($books as $book) : ?>
      <?php if($book['book_image']): ?>
        <a class="book grow image" href="book.php?id=<?php echo $book['book_id']; ?>"> <img class="book-image" src="book-covers/<?php echo $book['book_image'];?>"></a>
      <?php else: ?>
        <a class="book grow text" href="book.php?id=<?php echo $book['book_id']; ?>">Book text here</a>
      <?php endif; ?>
  <?php endforeach; ?>
</section>
Chris Haas
  • 53,986
  • 12
  • 141
  • 274
0

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 class="books">
<?php foreach ($books as $book) : ?>
    <a class="book grow" 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 class="book-image" src="book-covers/'.$book["book_image"].'">' : '<span class="book title">'.$book["book_title"].'</span>';
        ?>
    </a>
<?php endforeach; ?>
</section>

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

Monnomcjo
  • 715
  • 1
  • 4
  • 14