0

I am working on building a site, but right now it has several images that I don't have actual images for yet. As this site has thousands of images or places where images should be, I don't want to have to manually change each of them and then change them again when I find the correct image. Is there a way to create a function that will look for the missing images and replace them with a specified image until the correct image is found?

Update: Since I am still a bit confused as to where to even place this function, I am going to add the code for one of the pages that I need this for then maybe someone can help me figure out how to place it.

Here is the code for one of the pages:

<?php
require_once('dbconnection.php');
mysqli_select_db($conn, $dbname);
$query_master = "SELECT DISTINCT * FROM `master_list` INNER JOIN types_join ON master_list.join_id=types_join.join_id WHERE `type_id` = 171 ORDER BY `item_id`";
$master = mysqli_query($conn, $query_master) or die(mysqli_error());
$row_master = mysqli_fetch_assoc($master);
$totalrows_master = mysqli_num_rows($master);
?>

<!doctype html>
<html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Flower Trees</title>
<link href="/css/styles.css" rel="stylesheet" type="text/css">
<link rel="shortcut icon" type="image/png" href="img/favicon.png">
</head>

<body>

<div class="wrapper">
    <a id="top"></a>
    <?php require_once('header.php'); ?>
    <?php require_once('nav.php'); ?>
    <div class="category"><h2>Flower Trees</h2></div>           
    <div class="display">
      <?php do { ?>
      <ul>
          <li><a href="details.php?recordID=<?php echo $row_master['master_id']; ?>"><img class="thumb" src="img/<?php echo $row_master['img']; ?>"/>
          <br />
          <span class="name"><?php echo $row_master['name']; ?></span></a></li>
      </ul>
      <?php } while ($row_master = mysqli_fetch_assoc($master)); ?>
    <!-- end .display --></div>
    <?php
    mysqli_free_result($master);
    ?>
    <?php require_once('footer.php'); ?>
<!-- end .wrapper --></div>

<script>
function myFunction() {
  var x = document.getElementById("myTopnav");
  if (x.className === "topnav") {
    x.className += " responsive";
  } else {
    x.className = "topnav";
  }
}
</script>
</body>
</html>
Hevnlymom
  • 79
  • 11
  • You have an error. [`mysqli_error()`](https://www.php.net/manual/en/mysqli.error.php) needs one argument. Please consider switching error mode on instead. [How to get the error message in MySQLi?](https://stackoverflow.com/a/22662582/1839439) – Dharman Oct 30 '19 at 22:22

3 Answers3

1

I don't want to have to manually change each of them and then change them again when I find the correct image. Is there a way to create a function that will look for the missing images and replace them with a specified image until the correct image is found?

Such a function might be written as:

function im($imgName) {
    $pathToImgs = "images/";
    if (file_exists( $pathToImgs . $imgName )) {
        echo $pathToImgs . $imgName;
    }
    else {
        echo $pathToImgs . "placeholder.jpg";
    }
}

Then in your html:

<img src="<?php im("product1.jpg"); ?>">
<img src="<?php im("product2.jpg"); ?>">
<img src="<?php im("product3.jpg"); ?>">

As a start.

***Edit 1:

Given your code where it says:

<img class="thumb" src="img/<?php echo $row_master['img']; ?>"/>

You might modify it with a conditional that inserts the placeholder image in the event that the target image simply doesn't exist, yet.

<img class="thumb" src="<?php 

    if (file_exists("img/" . $row_master['img'])) {
        echo "img/" . $row_master['img'];
    }
    else {
        echo 'img/placeholder.jpg';
    }

?>">

You could reuse this functionality by turning the conditional into a php function, so described as a starter above.

GetSet
  • 1,511
  • 2
  • 10
  • 13
1

Since this is as simple as a foreach loop, and not tons of images scattered across your webpage, you can use something like:

$image = file_exists('img/' . $row_master['img']) ? 'img/' . $row_master['img'] : 'placeholder.png';

Full code:

<?php
require_once('dbconnection.php');
mysqli_select_db($conn, $dbname);
$query_master = "SELECT DISTINCT * FROM `master_list` INNER JOIN types_join ON master_list.join_id=types_join.join_id WHERE `type_id` = 171 ORDER BY `item_id`";
$master = mysqli_query($conn, $query_master) or die(mysqli_error());
$row_master = mysqli_fetch_assoc($master);
$totalrows_master = mysqli_num_rows($master);
?>

<!doctype html>
<html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Flower Trees</title>
<link href="/css/styles.css" rel="stylesheet" type="text/css">
<link rel="shortcut icon" type="image/png" href="img/favicon.png">
</head>

<body>

<div class="wrapper">
    <a id="top"></a>
    <?php require_once('header.php'); ?>
    <?php require_once('nav.php'); ?>
    <div class="category"><h2>Flower Trees</h2></div>           
    <div class="display">
      <?php do { 
          $image = file_exists('img/' . $row_master['img']) ? 'img/' . $row_master['img'] : 'placeholder.png';
      ?>
      <ul>
          <li><a href="details.php?recordID=<?php echo $row_master['master_id']; ?>"><img class="thumb" src="<?php echo $image; ?>"/>
          <br />
          <span class="name"><?php echo $row_master['name']; ?></span></a></li>
      </ul>
      <?php } while ($row_master = mysqli_fetch_assoc($master)); ?>
    <!-- end .display --></div>
    <?php
    mysqli_free_result($master);
    ?>
    <?php require_once('footer.php'); ?>
<!-- end .wrapper --></div>

<script>
function myFunction() {
  var x = document.getElementById("myTopnav");
  if (x.className === "topnav") {
    x.className += " responsive";
  } else {
    x.className = "topnav";
  }
}
</script>
</body>
</html>
Blue
  • 22,608
  • 7
  • 62
  • 92
  • I actually copied your code and put it in the place of mine after saving mine separately for safety. This code did not change anything. – Hevnlymom Oct 22 '19 at 20:30
  • 1
    It did. You just need to create an image file for `placeholder.png` – GetSet Oct 22 '19 at 20:34
  • I changed the name placeholder.png to my image of no_image.png and it still didn't change anything. – Hevnlymom Oct 22 '19 at 20:36
  • Since you copied pasted directly, you likely didnt notice that `placeholder.png` in the code is not stored to `img/` but in the parent folder – GetSet Oct 22 '19 at 20:38
  • yes, after adding img/ to the no_image.png, it works. ty. – Hevnlymom Oct 22 '19 at 20:42
  • Now to add it to all the pages. – Hevnlymom Oct 22 '19 at 20:46
  • You have an error. [`mysqli_error()`](https://www.php.net/manual/en/mysqli.error.php) needs one argument. Please consider switching error mode on instead. [How to get the error message in MySQLi?](https://stackoverflow.com/a/22662582/1839439) – Dharman Oct 30 '19 at 22:22
0

Using jQuery, you can accomplish something easy enough using a global $('img') handler when errors occur. Simply swap them out with your placeholder image afterwards.

$('img').on('error', function() {
  const oldSrc = encodeURIComponent($(this).attr('src'));
  $(this).attr('src', `https://via.placeholder.com/300/000000/FFFFFF/?text=${oldSrc}`);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img src="imagethatdoesntexist.jpg"><br />
<img src="anotherimage.jpg">

Here I use placeholder.com (A convenient site for placeholder images such as this), and inject the old image source into the query string, which the site will render in the image itself.

Blue
  • 22,608
  • 7
  • 62
  • 92
  • would that have to be put on each image on the site? I am talking about a site with thousands of images. – Hevnlymom Oct 22 '19 at 19:39
  • Like I said: It's a global script. Add it once to the page and ALL `$('img')` tags are picked. – Blue Oct 22 '19 at 19:40
  • The site has thousands of images or *will* have thousands of images? Also, whats your current approach to getting the images on the pages? Manually or automated, e.g. iterating over an array of images where their filenames are known? Or some other approach? – GetSet Oct 22 '19 at 19:48
  • @Getset, the images are being called from a database. The tables have the potential links for thousands of images, but many of the actual images are not there yet. – Hevnlymom Oct 22 '19 at 20:01
  • @GetSet It simply fires that function for every single `` that's rendered on the page. When it errors out, this function is fired, and replaces the source with a placeholder image. – Blue Oct 22 '19 at 20:04
  • FrankerZ, given the op's recent comment, the op knows beforehand that many images *will* not have links and thus why burden the DOM with an image onload thats never going to happen in those instances, and thus @Hevnlymom, why not simply insert that placeholder image (server-side or client-side) based on a condition of the record not having a defined image link? – GetSet Oct 22 '19 at 20:13
  • Again: Recent edit aside, yes, but he seemed like he wanted a quick and simple one off for handling ALL images across his site, which could have spanned multiple pages, multiple foreach loops or simply images embedded in static HTML. jQuery is a quick and simple one off solution, that will display placeholder images for all images with errors. I do agree though, that using a server side function is better, if it's just one loop. – Blue Oct 22 '19 at 20:15
  • Ok, He is a she, but that is neither here nor there. However, I don't care if it is server side or not, I just need something that works to fix the issue. I am building this site using information from several other places and therefore will be filling in the blanks as I go. – Hevnlymom Oct 22 '19 at 20:29
  • @FrankerZ, I do have an image that I can use for a placeholder it is no_image.png. However, would you please put your code into context for me so I can figure out how to place it? I am having a hard time wrapping my head around how to make that one work this time. – Hevnlymom Oct 22 '19 at 20:33
  • Also, yes, this does actually span multiple pages, but even if I have to add another php require, to all the pages that have these types of images, I won't mind. – Hevnlymom Oct 22 '19 at 20:35