user10701881
user10701881

Reputation:

How to retrieve an image on database and display avatar when image is null

I want to retrieve an image on my database,and I also want to retrieve images even it is null. now what i have on my image folder is an avatar, the avatar is also retrieve when the field is null. and when it is not null the image on the database will retrieve how can I do it ? how can I do it on this statement? thanks

here is my database connection

    <?php
session_start();
error_reporting(0);
include('includes/config.php');

$result = mysqli_query($db, "SELECT * FROM shopusers");

$id= $_SESSION['id'];
      $query = "SELECT * FROM shopusers WHERE id=$id";
      $results = mysqli_query($con, $query);
      $num=mysqli_fetch_assoc($results);

?>

here is my fetch query

 <?php
        $query=mysqli_query($con,"select * from shopusers where id='".$_SESSION['id']."'");
        while($row=mysqli_fetch_array($query))
        {
      ?>                    

           <?php 
           if($row == null){
              echo "<div class='avatar'><img src='img/avatar-6.jpg' alt='...' class='img-fluid rounded-circle'></div>";         
           }else{
            echo "<div class='avatar'><img src='users_image/".$row['image']."' alt='...' class='img-fluid rounded-circle'></div>";
           }

           ?>

      <?php } ?>

Upvotes: 0

Views: 471

Answers (1)

Jacob
Jacob

Reputation: 1926

  1. Storing images in database is not a good idea because your application will require more memory.
  2. Since OP mentioned it's a must to store in database, you can output it via data src.

           <?php 
           if(empty($row['image'])){
              echo "<div class='avatar'><img src='img/avatar-6.jpg' alt='...' class='img-fluid rounded-circle'></div>";         
           }else{
            echo '<div class="avatar"><img src="data:image/jpeg;base64,'.base64_encode( $row['image'] ).'"' alt="..." class="img-fluid rounded-circle"></div>';
           }
    
           ?>
    
      <?php } ?>
    

Upvotes: 1

Related Questions