gpt4 book ai didi

php - 如何让 PHP 打印来自 MySQL 数据库的评论数

转载 作者:行者123 更新时间:2023-11-29 07:00:10 25 4
gpt4 key购买 nike

我有以下问题。我有三个表:消息、评论和用户。我希望 PHP 将 MySQL 数据库中以下字段的数据作为表格打印在我的网页上:message.subject、user.username,然后是评论数。其他一切正常,但我还没有设法让 PHP 打印评论数。

这是我到目前为止尝试做的:

<?php
include("info.php");
$connect;
$sql="SELECT * FROM message, user
WHERE message.userID = user.userID AND
ORDER BY message.messageID DESC";
$result=mysql_query($sql) or die(mysql_error());

$sql2="SELECT message.messageID, COUNT(*) as comments FROM comment
INNER JOIN
message ON comment.messageID = message.messageID
GROUP BY comment.messageID";
$result2=mysql_query($sql2) or die(mysql_error());

<table>
<thead>
<tr>
<th>Subject</th>
<th>Sender</th>
<th>Number of comments</th>
</tr>
</thead>
<tbody>
<?php
while($rows=mysql_fetch_array($result)){
?>
<tr>
<td>
<a href="php/message.php?id=<?php echo $rows['messageID']; ?>">
<?php echo $rows['subject']; ?>
</td>
<td>
<?php echo $rows['username']; ?>
</td>
<td>
<?php while($rows2=mysql_fetch_array($result2)){ echo $rows2['comments'];}?>
</td>
</tr>
<?php
} mysql_close(); ?>
</tbody>
</table>

最佳答案

您不能通过一次查询获取所有这些信息吗?

SELECT
m.messageID,
m.subject,
u.username,
c.numOfComments
FROM
message m
INNER JOIN user u ON m.userID = u.userID
LEFT JOIN (SELECT COUNT(1) AS numOfComments, messageID FROM comments GROUP BY messageID) c ON m.messageID = c.messageID
ORDER BY
m.messageID DESC

试试这个脚本:

<?php
include("info.php");
connect();
$sql = "
SELECT
m.messageID,
m.subject,
u.username,
c.numOfComments
FROM
message m
INNER JOIN user u ON m.userID = u.userID
LEFT JOIN (SELECT COUNT(1) AS numOfComments, messageID FROM comments GROUP BY messageID) c ON m.messageID = c.messageID
ORDER BY
m.messageID DESC
";
$result = mysql_query($sql) or die(mysql_error());

echo "<table>
<thead>
<tr>
<th>Subject</th>
<th>Sender</th>
<th>Number of comments</th>
</tr>
</thead>
<tbody>\n";
while ($row = mysql_fetch_assoc($result))
{
$row = array_map("htmlspecialchars", $row); // sanitize to prevent XSS

echo " <tr>
<td><a href=\"php/message.php?id={$row["messageID"]}\">{$row["subject"]}</a></td>
<td>{$row["username"]}</td>
<td>{$row["numOfComments"]}</td>
</tr>\n";
}
echo " </tbody>
</table>";
?>

还有一些其他的更正。例如,您的链接没有结尾 </a>标记,您的脚本可能容易受到 XSS 攻击。然后是嵌套的 while 循环,它导致了不必要的复杂化和错误。

关于php - 如何让 PHP 打印来自 MySQL 数据库的评论数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10640433/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com