php - 收藏夹:在 'echo' 内动态加载适当的图标?

标签 php mysql nested favorites

我正在尝试在网站上实现收藏夹系统,例如在 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\..."

    }
?>

这是我的数据库:

enter image description here

如何让应用程序记住当前访问者的收藏夹并显示相应的图标$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";
       }
   }

我收到以下错误消息(另请参阅上面的代码注释):

  1. 警告:mysql_fetch_array() 期望参数 1 是 C:\xampp\htdocs 中给出的资源、对象...
  2. 注意: undefined variable :img_name 在 C:\xampp\htdocs...

谢谢!

最佳答案

使用连接:

"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']}"

关于php - 收藏夹:在 'echo' 内动态加载适当的图标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24147744/

相关文章:

php - 如何回显多维数组?

php - Laravel 重定向->back() 返回空参数

php - 按时间顺序从不同表中获取帖子

php - mysql+php : how to store a html string AS IS

php - 我的行的堆栈值而不是多个

mysql - MySQL 数据库中长度为 384 的 VARCHAR 字段的索引

python - 关于使我的 JSON find-all-nested-occurrences 方法更清晰的建议

silverlight - Silverlight 中嵌套类内的绑定(bind)属性

php - 删除多个空格

python - 带有初始化值的嵌套 FOR 循环,但继续整个列表范围