任何人都可以告诉我为什么这行被插入我的数据库两次?

时间:2016-11-16 23:10:05

标签: php mysql

当我点击我的''创建'按钮我希望将记录添加到我的类别表中,但由于某种原因,它会被添加两次 - 即使我只是单击按钮一次。任何想法为什么会这样?我无法看到其他地方 可以调用if (isset($_POST['create'])) {。我的整个项目只有4页。

<?php require('dbConnect.php'); 

    //use the variables we created in volleyLogin.php
        session_start();
        $username = $_SESSION['username'];
        $user_id = $_SESSION['user_id'];
        echo "user name is " . $username . "<br>";
        echo "user id is " . $user_id . "<br>"; 

    if (isset($_POST['create'])) {

        $category = ($_POST['category']);
        $name = ($_POST['name']);
        $phonenumber = ($_POST['phonenumber']);
        $address = ($_POST['address']);
        $comment = ($_POST['comment']);

    //check if the category being entered is already there
        $check="SELECT COUNT(*) FROM category WHERE cat_name = '$_POST[category]'";
        $get_value = mysqli_query($con,$check);
    //check the number of values of the category being posted
        $data = mysqli_fetch_array($get_value, MYSQLI_NUM);
    //if the category name already exists in the category table
        if($data[0] >= 1) {
        echo "This Already Exists<br/>";
         }

        else if ($data[0] < 1)
        {
    //if it's not in there, then add the category in the category table.

        $sql = "INSERT INTO category VALUES(NULL, '{$category}', '$user_id')";
        $rs1=mysqli_query($con, $sql); 

        if ($con->query($sql) === TRUE) {
        echo "Yes, it's been added correctly";

        } else {
        echo "Error: " . $sql . "<br>" . $con->error;
        }

        }
    $con->close();
        }



    ?>

        <!doctype html>
        <html>
        <body>
        <h2>Create new Contact</h2>
        <form method="post" action="" name="frmAdd">
        <p><input type="text" name = "category" id = "category" placeholder = "category"></p>
        <p><input type="text" name = "name" id = "name" placeholder = "name"></p>
        <p><input type="text" name = "phonenumber" id = "phonenumber" placeholder = "phone number"></p>
        <p><input type="text" name = "address" id = "address" placeholder = "address"></p>
        <p><input type="text" name = "comment" id = "comment" placeholder = "comment"></p>

        <p><input type="submit" name = "create" id = "create" value = "Create new Contact"></p>
        <a href="exit.php">Exit</a>

        </form>

        </body>
        </html>

1 个答案:

答案 0 :(得分:4)

您使用两种不同的方法运行$sql查询两次:

$rs1=mysqli_query($con, $sql); 

        if ($con->query($sql) === TRUE) {

这就是您获得重复条目的原因。

您应该删除$rs1,因为它没有被使用,或者在条件上验证它的值,而不是再次运行该功能。