抱歉,标题很长。 我有一个注册用户列表,有些有个人资料图片,有些没有。 问题是,如果用户 1 已登录。那么在用户列表中,每个人都有与用户 1 相同的个人资料图片。
但是,如果我从查询中删除默认调用者,每个用户都会获得自己的图片,但 default.jpg 图像不起作用。 我可以删除查询并在页面上使用 if 语句,但我真的想避免这种情况。
function fetch_users($uid){
$query = $this->link->query( "SELECT user.id, user.username, user.email,
userdetails.profile_img,userdetails.firstname,
userdetails.lastname,userdetails.location,following.follow_id
FROM user
LEFT JOIN userdetails ON user.id = userdetails.user_id
LEFT JOIN following ON user.id = following.follow_id
WHERE user.id != '{$uid}' ");
$users = array();
while(($row = $query->fetch(PDO::FETCH_ASSOC)) !== FALSE) {
#The row that mess up things#----->$row['profile_img'] = file_exists("img/{$uid}.jpg") ? "img/{$uid}.jpg" : "img/default.jpg" ;
$users[] = $row;
}
return $users;
}
最佳答案
你经常混合东西。在查询中,您从表中获取文件名,但在注释行中,您使用 uid 来构造名称。对于前者使用默认图像,您可以使用
SELECT …
IFNULL(userdetails.profile_img, "img/default.jpg") AS profile_img,
…
这会将表中的 NULL
值替换为默认图像的路径。
如果您想根据用户 ID 构建图像路径,那么您应该使用结果行中的 ID,而不是当前用户的 ID:
while(($row = $query->fetch(PDO::FETCH_ASSOC)) !== FALSE) {
$imgpath = "img/" . $row['id'] . ".jpg";
if (!file_exists($imgpath)) $imgpath = "img/default.jpg";
$row['profile_img'] = $imgpath;
$users[] = $row;
}
这将根据用户 ID 创建一个图像路径,如果不存在此类文件,则回退到默认值。
你甚至可以将它们结合起来:
SELECT …
IFNULL(userdetails.profile_img,
CONCAT("img/", user.id, ".jpg") AS profile_img,
…
while(($row = $query->fetch(PDO::FETCH_ASSOC)) !== FALSE) {
if (!file_exists($row['profile_img']))
$row['profile_img'] = "img/default.jpg";
$users[] = $row;
}
这将使用设置的存储图像路径,但否则使用从 uid 构造的路径。然后它将使用以这种方式命名的文件,但如果不存在这样的文件,则使用默认值。
关于mysql - 从查询中调用默认图像时,为每个用户获取唯一的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16216070/