我正在尝试在一个像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";
}
}我得到以下错误消息(还请参阅上面的代码注释):
谢谢!
发布于 2014-06-10 17:59:19
使用连接:
"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']}"发布于 2014-06-11 07:51:49
感谢Fred的提示(将mysql_fetch_array替换为mysqli_fetch_array),并将一个$img_name的声明从嵌套的“而我能够使代码工作”中移出。
嵌套查询的新代码(插入上述代码):
$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";
}
}https://stackoverflow.com/questions/24147744
复制相似问题