数据库上的重复数据

时间:2016-06-20 11:17:11

标签: php mysql sql

当我点击提交按钮时,在数据库中一次两个数据保存一个是重复的。我在下面显示我的代码

<?php
if (isset($_POST['submit'])) {
    function email_subscription($data)
    {
        $db_connect = mysqli_connect('localhost', 'root', '');
        if ($db_connect) {
            $db_select = mysqli_select_db($db_connect, 'db_seip_php28');

            if ($db_select) {
                echo "Database Selected";
            } else {
                echo "Database Not Selected";
            }
        } else {
            die('Connection Fail' . mysqli_error($db_connect));
        }

        $sql = "INSERT INTO db_newsletter(email_address) VALUES ('$data[email_address]')";

        mysqli_query($db_connect, $sql);
        if (mysqli_query($db_connect, $sql)) {
            echo "  Email address save successfully";
        } else {
            echo "Sorry May be some error happen";
        } 


    email_subscription($_POST);
} ?>

2 个答案:

答案 0 :(得分:4)

您执行了2次查询!

    mysqli_query($db_connect, $sql);       
    if (mysqli_query($db_connect, $sql))

答案 1 :(得分:1)

1)重要的是mysql查询执行了两次。

2)缺少if语句的紧密括号。

3)函数调用应该在函数外部。

    <?php
    if (isset($_POST['submit'])) 
    {
        function email_subscription($data)
        {
            $db_connect = mysqli_connect('localhost', 'root', '');
            if ($db_connect) {
                $db_select = mysqli_select_db($db_connect, 'db_seip_php28');

                if ($db_select) {
                    echo "Database Selected";
                } else {
                    echo "Database Not Selected";
                }
            } else {
                die('Connection Fail' . mysqli_error($db_connect));
            }

            $sql = "INSERT INTO db_newsletter(email_address) VALUES ('$data[email_address]')";

           // here query should be execute once only  . your executing twice here take look your code 
            if (mysqli_query($db_connect, $sql)) {
                echo "  Email address save successfully";
            } else {
                echo "Sorry May be some error happen";
            } 


    }

        email_subscription($_POST);  //function call should be in outside of function 

    } //missing close parenthesis  of if statement here

    ?>