为什么每次刷新浏览器时数据库都会更新?

时间:2016-05-17 20:40:05

标签: php html mysql

我的代码出现了问题,但我不知道是什么。我创建了一个非常基本的音乐库输入表单,它保存到mySQL表并将数据输出到屏幕。 出于某种原因,每次刷新浏览器页面并保存到数据库时它都会更新。谁能告诉我这里哪里出错了?谢谢,蒂姆

<?php
    //connect
    $link = mysqli_connect("localhost", "my_username", "mypassword", "mydb");

    //create user feedback if library has been updated
    if(isset($_POST['submit'])) {
        $cleanartist = mysqli_real_escape_string($link, $_POST['Artist']);
        $cleantitle = mysqli_real_escape_string($link, $_POST['Title']);

        //create query statement
        $sql = "INSERT INTO albums (Artist, Title) VALUES ('$cleanartist', '$cleantitle')";

        //run query
        mysqli_query($link, $sql);

        echo "Thanks, added to library";
    }

    mysqli_close($link);
?>


<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Music Library</title>
    </head>
    <body>
        <form class="" action="music_library.php" method="post">
            <p>Add Artist<input type="text" name="Artist"></p>
            <p>Album Title<input type"text" name="Title"></p>
            <input type="submit" name="submit" value="submit">
        </form>

        <?php

            //connect to db
            $link = mysqli_connect("localhost", "my_username", "mypassword", "mydb");

            //create query statement
            $qry = "SELECT * FROM albums";

            //run query and store result in variable
            $result = mysqli_query($link, $qry);

            //loop through returned data and output to screen
            while($row = mysqli_fetch_assoc($result)) {
                echo '<tr>';
                foreach($row as $field) {
                    echo '<td>' . $field . '</td>' . '</br>';
                }
            }

            mysqli_close($link);

        ?>

    </body>
</html>

2 个答案:

答案 0 :(得分:0)

当您在向其提交数据之前刷新页面时,它再次提交! 使用此函数将数据存储到数据库后,您可以简单地取消设置变量:

unset($_POST['submit']);

答案 1 :(得分:-1)

您可以在这两个答案中找到一些提示

PHP Redirect to another page after form submit

PHP header() redirect with POST variables

基本上,当操作成功时,你需要调用header("Location: music_library.php");