php - 在 foreach 循环内运行第二个查询?

标签 php mysql sql pdo foreach

需要在 foreach 中运行 2 个查询,但无法在没有错误的情况下完成。

所以,我用这个来显示评论:

$query = 'SELECT * FROM comments WHERE updatepostid = "' . $postID . '"';
    try {
        $stmt = $db->prepare($query);
        $stmt->execute();
        $countcomments = $stmt->rowCount();
        }
        catch (PDOException $ex) 
        {
            die("Failed to run query: " . $ex->getMessage());
        }

$rows = $stmt->fetchAll();
foreach ($rows as $row):
$commentID       = $row['commentID'];
$usercommentID   = $row['userID'];
$commentusername = ucfirst($row['commentusername']);
$comment         = ucfirst($row['comment']);
$updatepostid    = $row['updatepostid'];

<div class="textcomment">
    <?php
        echo "<a class='$rightscommentcolor'>$commentusername:</a>&nbsp; $comment";
    ?>
</div>


<?php endforeach; ?>

然后,我想在用户数据库上运行另一个查询来检查用户拥有哪些权限,然后将评论用户名的类别设置为该类别。

该查询将是例如

    <?php

$query2 = 'SELECT * FROM users WHERE id = "' . $usercommentID . '"';
    try {
        $stmt = $db->prepare($query2);
        $stmt->execute();
        }
        catch (PDOException $ex) 
        {
            die("Failed to run query: " . $ex->getMessage());
        }

$rows = $stmt->fetchAll();
foreach ($rows as $row):
$rights = $row['rights'];

if ($rights = '1') {
    $rightscommentcolor = 'userrights1';
} else if ($rights = '5') {
    $rightscommentcolor = 'userrights5';
}

?>
<?php endforeach; ?>

正确的方法是什么?

附注我知道上面的代码可能会让人哭。

最佳答案

使用带有联接的单个查询。另外,由于您使用的是 PDO,因此应该使用参数化查询而不是连接字符串。

$query = "SELECT * FROM comments c
          JOIN users u ON u.id = c.userID
          WHERE updatepostid = :updatepostid";
try {
    $stmt = $db->prepare($query);
    $stmt->execute(array(':updatepostid' => $postID));
    }
catch (PDOException $ex) 
    {
        die("Failed to run query: " . $ex->getMessage());
    }

关于php - 在 foreach 循环内运行第二个查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19778169/

相关文章:

mysql - 如何从 date_sub 中排除周末?

mysql - 从基于其他数据库mysql的表中删除

mysql - 如何选择二进制数据类型列并在 MySQL 中显示为人类可读的格式

mysql - 单个查询 MySQL 中的多个 SQL 别名

php - 拉拉维尔 5.6 : Many-to-many relationship returns empty object

php - 使用 DOMDocument PHP 获取 Xpath 父节点?

sql - 带有 CASE 语句的 PostgreSQL 慢连接

mysql - 如何使用 SQL 创建文件夹

php - 从 Controller 重定向后在 Laravel 中显示错误消息

Javascript 在本地工作,不会在网络服务器上工作