为什么每次f5(刷新)都是我的网站将数据插入数据库

时间:2018-01-23 07:10:56

标签: php mysql

我有一个使用mysql将数据插入数据库的表单。当我单击提交(添加数据)时,数据将成功插入数据库。但是,当我按f5(刷新)时,数据仍然插入数据库。我不知道我错在哪里。请帮我。这是我的代码:

<?php
$username = "user_tintuc"; // Khai báo username
$password = "123456";      // Khai báo password
$server   = "localhost";   // Khai báo server
$dbname   = "tintuc";      // Khai báo database

// Kết nối database tintuc
$connect = new mysqli($server, $username, $password, $dbname);

//Nếu kết nối bị lỗi thì xuất báo lỗi và thoát.
if ($connect->connect_error) {
    die("Không kết nối :" . $conn->connect_error);
    exit();
}

//Khai báo giá trị ban đầu, nếu không có thì khi chưa submit câu lệnh insert sẽ báo lỗi
$title = "";
$date = "";
$description = "";
$content = "";

//Lấy giá trị POST từ form vừa submit
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if(isset($_POST["title"])) { $title = $_POST['title']; }
    if(isset($_POST["date"])) { $date = $_POST['date']; }
    if(isset($_POST["description"])) { $description = $_POST['description']; }
    if(isset($_POST["content"])) { $content = $_POST['content']; }

    //Code xử lý, insert dữ liệu vào table
    $sql = "INSERT INTO tin_xahoi (title, date, description, content)
    VALUES ('$title', '$date', '$description', '$content')";

    if ($connect->query($sql) === TRUE) {
        echo "Thêm dữ liệu thành công";
    } else {
        echo "Error: " . $sql . "<br>" . $connect->error;
    }
}
//Đóng database
$connect->close();
?>

<form action="" method="post">
    <table>
        <tr>
            <th>Tiêu đề:</th>
            <td><input type="text" name="title" value=""></td>
        </tr>

        <tr>
            <th>Ngày tháng:</th>
            <td><input type="date" name="date" value=""></td>
        </tr>

        <tr>
            <th>Mô tả:</th>
            <td><input type="text" name="description" value=""></td>
        </tr>

        <tr>
            <th>Nội dung:</th>
            <td><textarea cols="30" rows="7" name="content"></textarea></td>
        </tr>
    </table>
    <button type="submit">Gửi</button>
</form>

我这样编辑了。但它仍然是那样。

if (isset($_POST['submit'])){
    if(isset($_POST["date"])) { $date = $_POST['date'];}
    if(isset($_POST["MAB"])) { $MAB = $_POST['MAB']; }
    if(isset($_POST["MBA"])) { $MBA = $_POST['MBA']; }
    if(isset($_POST["PAB"])) { $PAB = $_POST['PAB']; }
    if(isset($_POST["PBA"])) { $PBA = $_POST['PBA']; }

$sql = "INSERT INTO `dbsht` (`date`, `MAB`, `MBA`, `PAB`, `PBA`) VALUES ('$date', '$MAB', '$MBA', '$PAB', '$PBA')"; 
    if ($connect->query($sql) === TRUE) {
        echo "Thêm dữ liệu thành công";
    } else {
        echo "Error: " . $sql . "<br>" . $connect->error;
    }
} 

3 个答案:

答案 0 :(得分:1)

这是正常问题。您应该使用POST-Redirect-GET模式来阻止它。插入数据库成功后,您应该使用重定向响应GET请求。

您可以尝试

    if ($connect->query($sql) === TRUE) {
        $_SESSION["ADD_SUCCESS"] = 1;

        header('Location: '.$_SERVER['REQUEST_URI']);
    } else {
        echo "Error: " . $sql . "<br>" . $connect->error;
    }

成功留言

    //Đóng database
    $connect->close();

    if(isset($_SESSION["ADD_SUCCESS"])) 
    { 
        echo "Chúc mừng bạn đã thêm dữ liệu thành công";

        unset($_SESSION["ADD_SUCCESS"]); 
    }

答案 1 :(得分:0)

你可以解决它,但不要重新组织它并重写它,因为你的方法是边界线可怕的。 将myform.html作为一个文件,将用于在db中插入数据的php代码作为另一个文件(如db_insert.php)以及用于db连接的数据(用户,pass,db,host)放在公共文件夹的单独文件OUTSIDE中(在public_html之外或其他任何内容)例如,在文件config.inc.php中。这样做,你就可以避免你现在和其他许多人遇到的这个问题。

所以在 myform.html 中输入数据并提交=&gt; db_insert.php 从myform.html获取数据,从 config.inc.php 获取数据,在数据库中输入数据并重定向回myform.html或您的其他部分应用

在您完成工作并弄清楚如何以及为什么之后,请阅读一些关于AJAX的文章以及如何在不离开您的表单页面的情况下完成相同的工作。很明显,你刚开始学习,所以一定要以正确的方式学习;)

答案 2 :(得分:0)

一旦POST请求被发送,php代码应该对数据进行必要的逻辑测试和卫生例程,构造并执行sql,最后重定向到同一页面或另一个页面。重定向将阻止在刷新页面时重新提交表单

<?php

    $message='';

    if( $_SERVER['REQUEST_METHOD']=='POST' ){
        try{

            $username = "user_tintuc";
            $password = "123456";
            $server   = "localhost";
            $dbname   = "tintuc";   
            $connect = new mysqli( $server, $username, $password, $dbname );

            $title = isset( $_POST["title"] ) ? $_POST["title"] : false;
            $date = isset( $_POST["date"] ) ? $_POST["date"] : false;
            $description = isset( $_POST["description"] ) ? $_POST["description"] : false;
            $content = isset( $_POST["content"] ) ? $_POST["content"] : false;

            if( $title && $date && $description && $content ){

                $sql = 'insert into `tin_xahoi` ( `title`, `date`, `description`, `content`) values (?,?,?,?)';
                $stmt=$connect->prepare( $sql );

                if( $stmt ){

                    $stmt->bind_param('ssss',$title,$date,$description,$content);
                    $result=$stmt->execute();
                    $stmt->close();

                    /* set a temporary session variable - used to display message */
                    $_SESSION['dbstatus']=$result ? 'Record added' : 'Sorry - an error occurred';

                    header('Location: ?status=' . ( $result ? 'ok' : 'error' ) );

                } else {
                    throw new Exception('Failed to prepare sql');
                }
            } else {
                throw new Exception('one or more variables are empty');
            }
        }catch( Exception $e ){
            $message=sprintf('<p>%s</p>',$e->getMessage());
        }
    }
?>
<!doctype html>
<html>
    <head>
        <meta charset='utf-8' />
        <title></title>
    </head>
    <body>
        <form method="post">
            <table>
                <tr>
                    <th>Tiêu d?:</th>
                    <td><input type="text" name="title" value=""></td>
                </tr>

                <tr>
                    <th>Ngày tháng:</th>
                    <td><input type="date" name="date" value=""></td>
                </tr>

                <tr>
                    <th>Mô t?:</th>
                    <td><input type="text" name="description" value=""></td>
                </tr>

                <tr>
                    <th>N?i dung:</th>
                    <td><textarea cols="30" rows="7" name="content"></textarea></td>
                </tr>
            </table>
            <button type="submit">G?i</button>
            <?php

                /* Display the message from session variable and unset the variable */
                if( !empty( $_GET['status'] ) && isset( $_SESSION['dbstatus'] ) ) {
                    $message=$_SESSION['dbstatus'];
                    unset( $_SESSION['dbstatus'] );
                }

                /* Display whatever is in $message */
                echo $message;

            ?>
        </form>
    </body>
</html>