表格从所有用户插入数据重复次数

时间:2013-07-12 01:53:33

标签: php mysql insert records

我无法弄清楚原因,但每当用户在我正在处理的网站上发帖时,它都会多次发布到数据库,网站上每个成员1个条目(目前为3个)。

这是我的代码。

Add_topic.php

$category=$_POST['category'];
$sub_category=$_POST['sub_category'];
$topic_data=$_POST['topic_data'];
$posted=date("h:i:s d/m/Y"); //create date time

$sql = "INSERT INTO `topics`(category, sub_category, topic_data, posted_by, posted)VALUES('$category', '$sub_category', '$topic_data', '".$_SESSION['user_id']."', '$posted')";
$result=mysql_query($sql);

if($result){
header("Location: topics.php?category=$category&sub_category=$sub_category");
exit();
}

Topics.php

$sql = "SELECT users.user_id, users.username, users.profile, topics.topic_id, topics.category, topics.sub_category, 
topics.topic_data, topics.posted_by, topics.posted, topics.view, topics.reply 
FROM users, topics WHERE topics.category = '" . $_GET['category'] . "' AND  topics.sub_category = '" . $_GET['sub_category'] . "' ORDER BY topics.posted DESC";

$result = mysql_query($sql);

while($rows = mysql_fetch_array($result)){

1 个答案:

答案 0 :(得分:0)

我认为add_topic.php不会插入多行。您可以直接查看表格来验证这一点。

我认为您的问题是Topics.php中的查询。

$sql = "SELECT users.user_id, users.username, users.profile, topics.topic_id,
               topics.category, topics.sub_category, topics.topic_data, 
               topics.posted_by, topics.posted, topics.view, topics.reply 
        FROM users, topics 
        WHERE topics.category = '" . $_GET['category'] . "' 
        AND  topics.sub_category = '" . $_GET['sub_category'] . "' 
        ORDER BY topics.posted DESC";

您正在userstopics进行加入,但您没有定义链接它们的内容。因此,它为每个主题帖子的每个用户创建一行。

您可以将其视为此SQLFiddle的第一个示例结果集 - http://sqlfiddle.com/#!2/7dfc4/4

您要做的是LEFT JOIN用户对主题ON topics.posted_by = users.user_id

这是第二个示例结果集 - http://sqlfiddle.com/#!2/7dfc4/4

因此,您的查询现在是(转义$_GET以防止SQL注入) -

$sql = "SELECT users.user_id, users.username, users.profile, topics.topic_id,
               topics.category, topics.sub_category, topics.topic_data, 
               topics.posted_by, topics.posted, topics.view, topics.reply 
        FROM topics
        LEFT JOIN users
        ON topics.posted_by = users.user_id
        WHERE topics.category = '" . mysql_real_escape_string($_GET['category']) . "' 
        AND  topics.sub_category = '" . mysql_real_escape_string($_GET['sub_category']) . "' 
        ORDER BY topics.posted DESC";

注意 - 您不应该在新代码中使用mysql_*函数。它从php v.5.5开始折旧。您应该将代码更新为mysqli_*PDOhttp://php.net/manual/en/mysqlinfo.api.choosing.php