How can I replace the picture, if it does not exist, either in the database (the image field is empty) or in the folder with photos ../uploads/ in php ?

Php code:

 <?php $query_art = mysql_query("SELECT * FROM `news`");?> <?php for($i = 0; $i < mysql_num_rows($query_art); ++$i): ?> <?php $array = mysql_fetch_array($query_art); ?> <?php $ar_image = $array['image']; ?> <?php if (!empty($ar_image)){ $image = $ar_image; } else { $image = "none_foto.png"; } ?> <img alt="Фото" src="../uploads/<?php echo $image; ?>" class="leftimg" /> <?php endfor; ?> 
  • one
    Make constants in any class that will point to a folder with default photos and a folder with downloaded photos ..... such as const UPLOAD_FOLDER = "../uploads/"; const IMAGES_FOLDER = "images"; const UPLOAD_FOLDER = "../uploads/"; const IMAGES_FOLDER = "images"; and then just substitute that constant, depending on the case ....... a la $image = (!empty($ar_image)) ? UPLOAD_FOLDER.$ar_image : $image = IMAGES_FOLDER."none_foto.png"; $image = (!empty($ar_image)) ? UPLOAD_FOLDER.$ar_image : $image = IMAGES_FOLDER."none_foto.png"; ....... in the img tag it will just be already <img alt="Фото" src="<?= $image; ?>" class="leftimg" /> - Aleksey Shimansky
  • Thanks for the comment. I understand what constants are, but I don’t know how to apply it correctly, where should I insert it? - fedosov
  • Check in the uploads folder via file_exists - ilyaplot
  • @fedosov depends on what application you have. If classes are used and what is above is a view , then in the class you need to make constants that you declare once and then use them repeatedly. In the case of IMAGES_FOLDER , the good thing is to be stored in the application define('ИМЯ_КОНСТАНТЫ', значение) as define('ИМЯ_КОНСТАНТЫ', значение) .. and then you can simply use it through the name echo ИМЯ_КОНСТАНТЫ .. in class via const ИМЯ_КОНСТАНТЫ = значение; and then the use is as follows: echo ИмяКласса::ИМЯ_КОНСТАНТЫ; in your code how to use I wrote. + Do not forget file_exists as file_exists wrote - Alexey Shimansky

1 answer 1

 <?php $query_art = mysql_query("SELECT * FROM `news`"); while($array = mysql_fetch_array($query_art)) { $imageName = $array['image']; if (!($imageName && file_exists("/uploads/{$imageName}"))){ $imageName = "none_foto.png"; } ?> <img alt="Фото" src="../uploads/<?=$imageName?>" class="leftimg" /> <?php }