我正在尝试在网站上实施收藏系统,例如在stackoverflow.com上:如果您点击星形图标,图像将被交换以显示它现在是最喜欢的。就我而言,这不是问题,而是受到青睐的用户。到目前为止没有大问题。
但是,我希望PHP / MySQL能够记住哪些用户是当前访问者的最爱,并动态决定在加载页面时使用哪个相应的图标。 没有这个功能,我的(有点简化)代码如下所示:
<?php
$q = "SELECT id, username FROM users";
$r = mysqli_query($dbc, $q);
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
//Insert nested query here (explanation and code see below)
// Display each user:
echo '<div class="favorit"><input class="user_id" type="hidden" name="user_id" value="'.$row['id'].'"><img src="../img/ ' .$img_name. ' " alt="" class="icons"/><br>Favorit</div>'; //generates error "Notice: Undefined variable: img_name in C:\xampp\htdocs\..."
}
?>
这是我的数据库:
如何让应用程序记住当前访问者的收藏夹并显示相应的图标 $ img_name ?我的猜测是在上面的第一个中进行嵌套查询,但我无法让它工作:
嵌套查询代码(插入上面的代码中):
//query the favorites of the current visitor:
$q2 = "select favorite_id from favorites where users_id=" . $_SESSION['reg_user_id'] . "";
$r2 = mysqli_query($dbc, $q2);
//there may be more favorites, so loop through them:
while($row2 = mysql_fetch_array($r2, MYSQLI_ASSOC)){ //generates error "Warning: mysql_fetch_array() expects parameter 1 to be resource, object given in C:\xampp\htdocs\..."
//if the respective user is a favorite:
if($row2['favorite_id'] == $row['id']){
$img_name = "favorite_full.svg";
}
else {
$img_name = "favorite_contour.svg";
}
}
我收到以下错误消息(另见上面的代码注释):
谢谢!
答案 0 :(得分:1)
使用联接:
"SELECT u.id, u.username, f.favorite_id IS NOT NULL AS is_favorite
FROM users AS u
LEFT JOIN favorites AS f
ON u.id = f.favorite_id
AND f.users_id = {$_SESSION['reg_user_id']}"
答案 1 :(得分:0)
感谢Fred -ii - &#39; s提示(为mysqli_fetch_array交换mysql_fetch_array)并将一个$ img_name-instance的声明移出嵌套的#34;而#34;我能够使代码工作。
嵌套查询的新代码(插入上面的代码中):
$img_name = "favorit_kont.svg";
$q2 = "select favorite_id from favorites where users_id=" . $_SESSION['reg_user_id'] . "";
$r2 = mysqli_query($dbc, $q2);
//loop through favorites:
while($row2 = mysqli_fetch_array($r2, MYSQLI_ASSOC)){
//if the respective user is a favorite:
if($row2['favorite_id'] == $row['id']){
$img_name = "favorit.svg";
}
}