Home > front end >  Ignore echo function if database cell is empty (MySQL/PHP)
Ignore echo function if database cell is empty (MySQL/PHP)

Time:01-16

I am using Bootstrap cards with MySQL/PHP to echo data from a database/ table.

I have a column in the database "Favourite", this field is either empty or contains a path to an image.

If the corresponding database field is empty for a particular record, I would like to echo nothing. Right now, it is echoing a broken icon (probably because I'm using the img tag?).

Here is the first part of the code:

<?php
            include_once("conn.php");
            $sql = "SELECT * FROM table ORDER BY id ASC";
            $result = mysqli_query($conn, $sql);
            if(mysqli_num_rows($result) > 0)
            {
                while($row = mysqli_fetch_array($result))
                {
            ?>

Here is the echo function;

<img alt="Favourite" title="Favourite" src="http://localhost/Test/Images/Icons/<?php echo $row["Favourite"]; ?>" width="12.5%" height="12.5%"/>

I'm an amateur.. so would ideally like to make the solution as simple as possible.

Thanks in advance!

CodePudding user response:

<?php if(!empty($row["Favourite"])) { ?>
    <img alt="Favourite" title="Favourite" src="http://localhost/Test/Images/Icons/<?php echo $row["Favourite"]; ?>" width="12.5%" height="12.5%"/>
<?php } ?>

More on empty function: https://www.php.net/manual/en/function.empty.php

CodePudding user response:

This code will work, if favorite will not empty

<?php
            include_once("conn.php");
            $sql = "SELECT * FROM table ORDER BY id ASC";
            $result = mysqli_query($conn, $sql);
            if(mysqli_num_rows($result) > 0)
            {
                while($row = mysqli_fetch_array($result))
                {
                  $favourite = $row["Favourite"];
                }
           }

 if(!empty($favourite)) { 
    echo '<img alt="Favourite" title="Favourite" src="http://localhost/Test/Images/Icons/"'.$favourite.'width="12.5%" height="12.5%"/>';
 } 
else{
//rest of code
}
?>

CodePudding user response:

You need to make your echo function like this

<img alt="Favourite" title="Favourite" src="http://localhost/Test/Images/Icons/<?php echo $row["Favourite"]; ?>" width="100.5%" height="100.5%"/>

  •  Tags:  
  • Related