需要在 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> $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/