Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/298.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 为什么每次f5(刷新)是我的网站插入数据到数据库_Php_Mysql - Fatal编程技术网

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

Php 为什么每次f5(刷新)是我的网站插入数据到数据库,php,mysql,Php,Mysql,我有一个表单,它使用mysql将数据插入数据库。单击提交(添加数据)时,数据将成功插入数据库。但是,当我按f5(刷新)时,数据仍然插入到数据库中。我不知道我错在哪里。请帮帮我。这是我的代码: <?php $username = "user_tintuc"; // Khai báo username $password = "123456"; // Khai báo password $server = "localhost"; // Khai báo server $db

我有一个表单,它使用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>

您可以修复它,但不可以,重新组织并重写它,因为您的方法非常糟糕。
例如,将myform.html作为一个文件,将用于在db中插入数据的php代码作为另一个文件(如db_insert.php),将用于db连接的数据(user、pass、db、host)放在config.inc.php文件中公用文件夹(public_html或其他文件之外)之外的单独文件中。这样做,你就会避免这个问题,你现在和许多其他问题

因此,在myform.html中输入数据并提交=>db_insert.php从myform.html获取数据,从config.inc.php获取数据,在db中输入数据并重定向回myform.html或应用程序的其他部分


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

这是正常问题。您应该使用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;
    }

发送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>

蒂尤德:
Ngáy Thang:
Môt?:
N?i dung:
G?i

Do
POST
插入数据前检查<代码>如果($\u POST){//your\u stuff}
解决此问题的方法之一是一种模式,通常称为另一种模式,即每当您按下
CTRL+R
F5
时,浏览器将重新发布您的表单,您的条件将为真,数据已插入。@Hungtrin请使用英语或其他语言,主持人将对您进行否决或处罚。我还有另一个更改iframe标记中的url时出现问题。你能帮我吗?谢谢你的建议:)@博齐达尔·西坎基奇
    //Đó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"]); 
    }
<?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>