Reputation: 3368
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);
Upvotes: 1
Views: 41
Reputation: 135
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; ?>
Upvotes: 1
Reputation: 3780
You just need to initialize the variables before the if..else
statements so that it won't be undefined when you try to echo both of them.
$profile_img = "";
$default_profile_img = "";
if (...
Upvotes: 1
Reputation: 31
Try this code. There is no need to use two different variables. This way, you won't get the warning.
$pics = array();
while ($stmt->fetch()) {
$pics[] = $profilePic;
}
if (!isset($profilePic) OR $profilePic === NULL) {
$profile_img = '<img class="welcome-pic" src="profile_images/default.jpg">';
} else {
$profile_img = '<img class="welcome-pic" src=" '.$profilePic.'">';
}
}
?>
<nav id="nav-panel">
<div id="nav-container">
<div id="welcome">
<?php echo $profile_img; ?>
Upvotes: 0