Paul Paul - 1 month ago 7
PHP Question

Setting the result of an if statement

I am displaying a user's profile image. I have created an if statement to post a default profile image if a user has not updated their own. This is all working, but what I cannot figure out is how to echo or call for each without getting an error for the one not set.

For instance, if they do have a profile picture set, it posts fine, but then I get an error that the other variable is not defined and vise versa.

How should I be calling for this or what changes should I make in my code?

$pics = array();
while ($stmt->fetch()) {
$pics[] = $profilePic;
}
if ($profilePic === NULL) {
$default_profile_img = '<img class="welcome-pic" src="profile_images/default.jpg">';
} else {
$set_profile_img = '<img class="welcome-pic" src=" '.$profilePic.'">';
}
}
?>
<nav id="nav-panel">
<div id="nav-container">
<div id="welcome">
<?php echo $default_profile_img;
echo $set_profile_img; ?>


EDIT:

How profilepic gets defined:

$sql = "
SELECT *
FROM profile_img
WHERE user_id = ?
ORDER BY id DESC LIMIT 1
";
if ($stmt = $con->prepare($sql)) {
$stmt->bind_param("s", $user_id);
$stmt->execute();
if (!$stmt->errno) {
// Handle error here
}
$stmt->bind_result($id, $user_id, $profilePic);

Eyy Eyy
Answer

Just add $default_profile_img = null; and $set_profile_img = null; at the top of php code.

$default_profile_img = null;
$set_profile_img = null;
$pics = array();
    while ($stmt->fetch()) {
        $pics[] = $profilePic;
    }
    if ($profilePic === NULL) {
        $default_profile_img = '<img class="welcome-pic" src="profile_images/default.jpg">';
    } else {
        $set_profile_img = '<img class="welcome-pic" src=" '.$profilePic.'">';
    }
}
?>
<nav id="nav-panel">
<div id="nav-container">
        <div id="welcome">
            <?php echo $default_profile_img; 
            echo $set_profile_img; ?>
Comments