kenny kenny - 6 months ago 11
SQL Question

How to echo If statement from database

I'm having troubles displaying the information in the IF STATEMENT inside of the while loop. Is it even possible to echo an if statement inside a while loop? please help!

This code

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "databasename";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection

$searchEscaped = $conn->real_escape_string($_GET['username']);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT * FROM users WHERE username = '$searchEscaped' ";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "
**if(!empty($row['image2'])) {
<a class='example-image-link' href='pictures/".$row['image2']."' data-lightbox='example-set'><img class='example-image'src='pictures/".$row['image2']."' alt='Profile Pic'></a>
}
";}
} else {
echo "No users found";
}

$conn->close();
?>

Answer

I think you need to move your echo inside the if statement to only echo if the requirement is met:

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "databasename";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection

$searchEscaped = $conn->real_escape_string($_GET['username']);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT * FROM users WHERE username = '$searchEscaped' ";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while ($row = $result->fetch_assoc()) {

        if (!empty($row['image2'])) {
            echo "
    <a class='example-image-link' href='pictures/" . $row['image2'] . "' data-lightbox='example-set'><img class='example-image'src='pictures/" . $row['image2'] . "'  alt='Profile Pic'></a>

      ";
        }
    }
} else {
    echo "No users found";
}

$conn->close();
?>  

Here's an example of a function that would be usable throughout your script:

    function print_image($row_image){
        if(!empty($row_image)){
            return  "
        <a class='example-image-link' href='pictures/" . $row_image . "' data-lightbox='example-set'><img class='example-image'src='pictures/" . $row_image . "'  alt='Profile Pic'></a>

          ";
        }
else{
        return "";
    }
    }

you can call this function anywhere else in your script and do something like:

echo print_image($row['image2']);

or

echo print_image($row['image3']);