来自MySql的数据多次显示

时间:2014-10-13 10:23:34

标签: php mysql forms

这是我的SQL查询

$sql = "SELECT comments.comment, users.userid, comments.bpid 
       FROM comments, users ,blogpages
       WHERE comments.user_id = users.user and comments.bpid ='".$blogid."'
       ORDER BY comments.cid;"

$query = mysqli_query($con,$sql) or die (mysqli_error($con));

while($row = mysqli_fetch_array($query,MYSQLI_ASSOC)){
        $comm =$row["comment"]; 
        $commentsuser =$row["userid"];
        $commentbody .= "".$commentsuser."".$comm." ";      
}

这是我的表格和展示

<form action="" method="POST">
    <textarea  name="commentarea"></textarea>
    <input type="submit" value="COMMENT" >
    <h2><?php echo $commentbody; ?></h2>
</form>

但在我输入评论后,每个值都会多次显示?

在我重新进入页面之前,评论不会显示

2 个答案:

答案 0 :(得分:0)

您缺少连接条件:

SELECT   comments.comment, users.userid, comments.bpid 
FROM     comments, users ,blogpages
WHERE    comments.user_id = users.user AND
         comments.bpid = blogpages.id AND -- Missing in the OP
         comments.bpid ='".$blogid."'
ORDER BY comments.cid;

话虽如此,不推荐使用隐式连接,您可能应该使用显式连接:

SELECT   comments.comment, users.userid, comments.bpid 
FROM     comments
JOIN     users ON comments.user_id = users.user
JOIN     blogpages ON comments.bpid = blogpages.id 
WHERE    comments.bpid ='".$blogid."'
ORDER BY comments.cid;

这也有助于可视化您缺少的连接条件,因为在此表单中它是语法的实际部分。

答案 1 :(得分:0)

我认为您正在寻找的SQL就像......

SELECT 
    comments.comment, 
    users.userid, 
    comments.bpid
FROM 
    comments, 
    INNER JOIN users ON comments.userId = users.userid,
    INNER JOIN blogpages ON comments.bpid = blogpages.bpid
WHERE
    comments.bpid ='".$blogid."'
ORDER BY 
    comments.cid;