刷新PHP页面时,表内容会不断添加

时间:2013-10-27 12:44:58

标签: php sql database page-refresh

我在PHP中向数据库添加内容时遇到问题。每次刷新页面时,它都会再次添加完全相同的值。我怎么能让它停止这样做?我不知道为什么会这样做。

我希望它将值添加到数据库一次并将其存储在那里。创建表并添加值后,将在页面上使用它们。用户可以添加更多值。

它还会添加用户在刷新时输入的内容。

问题部分是

$db_query = 'INSERT INTO `cars`' .
    ' (`id`, `make`, `model`, `year`, `color`, `engine`)' .
    ' VALUES' .
    ' (NULL, \'Citroen\', \'Saxo\', \'1997\', \'White\', 1.1),' .
    ' (NULL, \'Citroen\', \'C3\', \'2012\', \'Blue\', 1.4),' .
    ' (NULL, \'Volkswagen\', \'Golf\', \'2010\', \'Blue\', 1.8),' .
    ' (NULL, \'Ford\', \'Mondeo\', \'2009\', \'Black\', 1.6),' .
    ' (NULL, \'Renault\', \'Clio\', \'2010\', \'Silver\', 1.2);';
$result = mysqli_query($conn, $db_query);

完整代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Task 7</title>
</head>
<body>
<?php


// connection to the database start
$host = 'localhost';
$user = 'root'; // your username
$password = 'vertrigo'; // your password
$databaseName = 'db2'; // your database

$conn = mysqli_connect($host, $user, $password, $databaseName);

if (mysqli_connect_errno($conn)) {
    echo 'Failed to connect to MySQL: ' . mysqli_connect_error();
} else {
    echo 'have connection<br>';
}
// connection to the database end (output messages created)


// creating table with rows start
$db_query = 'CREATE TABLE IF NOT EXISTS `cars` (' .
    '`id` int(11) NOT NULL AUTO_INCREMENT,' .
    '`make` varchar(50) NOT NULL,' .
    '`model` varchar(50) NOT NULL,' .
    '`year` varchar(4) NOT NULL,' .
    '`color` varchar(50) NOT NULL,' .
    '`engine` decimal(2,1) NOT NULL,' .
    'PRIMARY KEY (`id`));';
$result = mysqli_query($conn, $db_query);
// creating table with rows end


// putting info in each column start
$db_query = 'INSERT INTO `cars`' .
    ' (`id`, `make`, `model`, `year`, `color`, `engine`)' .
    ' VALUES' .
    ' (NULL, \'Citroen\', \'Saxo\', \'1997\', \'White\', 1.1),' .
    ' (NULL, \'Citroen\', \'C3\', \'2012\', \'Blue\', 1.4),' .
    ' (NULL, \'Volkswagen\', \'Golf\', \'2010\', \'Blue\', 1.8),' .
    ' (NULL, \'Ford\', \'Mondeo\', \'2009\', \'Black\', 1.6),' .
    ' (NULL, \'Renault\', \'Clio\', \'2010\', \'Silver\', 1.2);';
$result = mysqli_query($conn, $db_query);
// putting info in each end


// add cars START
@$cars = $_POST['cars'];
if (isset($cars)) {
    $db_query = "INSERT INTO cars (make, model, year, color, engine) VALUES ('".$cars['0']."','".$cars['1']."','".$cars['2']."','".$cars['3']."','".$cars['4']."')";
    mysqli_query($conn, $db_query);
} else {
    echo 'Cars array does not exists and obtained from FORM.';
}
// add cars END


// select cars table if right output the headers start
$db_query = "SELECT * FROM cars WHERE id <> 0 ORDER BY year ASC";

if ($result = mysqli_query($conn, $db_query)) {
    echo  "    <table border='1'>";
    echo  "        <tr><td>Make</td><td>Year</td><td>model</td><td>color</td><td>engine</td></tr>";
    // select cars table if right output the headers end

    // while start, output the content of the colum.
    while ($row = mysqli_fetch_assoc($result)) {
    ?>
        <tr>
            <td><?php echo $row['make']; ?></td>
            <td><?php echo $row['year']; ?></td>
            <td><?php echo $row['model']; ?></td>
            <td><?php echo $row['color']; ?></td>
            <td><?php echo $row['engine']; ?></td>
        </tr>
    <?php
    }
    // endwhile

    echo "</table>";
}
?>
    <form action="index.php" method="post" name="zatupok">
        <fieldset>
            <legend>MY CARS</legend>
            <label>Make</label>
            <input type="text" name="cars[]">
            <label>Model</label>
            <input type="text" name="cars[]">
            <label>Year</label>
            <input type="text" name="cars[]">
            <label>Color</label>
            <input type="text" name="cars[]">
            <label>Engine</label>
            <input type="text" name="cars[]">
            <input type="submit">
        </fieldset>
    </form>
</body>
</html>

1 个答案:

答案 0 :(得分:-1)

为什么在每次访问页面时添加样本值

每次访问页面时都会执行PHP代码。它生成页面(动态写入部分页面,只复制<?php … ?>之外的所有内容),页面是脚本的输出。 Apache或您使用的任何服务器软件只获取HTTP请求,执行您的脚本,获取其输出并通过HTTP响应将其发送到客户端。

如果您的INSERT查询无条件执行(按原样),则每次访问该页面时都会执行该查询。这就是为什么一次又一次地添加这些值。

如何停止添加样本值

您可能想要检查cars表是否已创建并仅在以下情况下执行插入查询:

// creating table with rows start
// CHANGED: Notice that IF NOT EXISTS is not used anymore!
//          Fails if table already exists, not touching its original contents.
$db_query = 'CREATE TABLE `cars` (' .
    '`id` int(11) NOT NULL AUTO_INCREMENT,' .
    '`make` varchar(50) NOT NULL,' .
    '`model` varchar(50) NOT NULL,' .
    '`year` varchar(4) NOT NULL,' .
    '`color` varchar(50) NOT NULL,' .
    '`engine` decimal(2,1) NOT NULL,' .
    'PRIMARY KEY (`id`));';
$result = mysqli_query($conn, $db_query);
// creating table with rows end


// putting info in each column start
$db_query = 'INSERT INTO `cars`' .
    ' (`id`, `make`, `model`, `year`, `color`, `engine`)' .
    ' VALUES' .
    ' (NULL, \'Citroen\', \'Saxo\', \'1997\', \'White\', 1.1),' .
    ' (NULL, \'Citroen\', \'C3\', \'2012\', \'Blue\', 1.4),' .
    ' (NULL, \'Volkswagen\', \'Golf\', \'2010\', \'Blue\', 1.8),' .
    ' (NULL, \'Ford\', \'Mondeo\', \'2009\', \'Black\', 1.6),' .
    ' (NULL, \'Renault\', \'Clio\', \'2010\', \'Silver\', 1.2);';
// CHANGED: Executing the query only if previous query (`CREATE TABLE …`) succeeded.
if ($result) {
    $result = mysqli_query($conn, $db_query);
}
// putting info in each end

POST问题后刷新

我们在调试问题时遇到的另一个问题是在POST表单提交后刷新。浏览器会自动再次提交原始表单内容,这是标准行为。它导致将提交的值再次插入数据库,现在将它们存储在两个甚至更多的副本中。

但这可以预防。参见例如Stop browsers asking to resend form data on refresh。接受的答案建议使用POST-redirect-GET模式,这是我在你的情况下会使用的模式。在googling post data resent stackoverflow时,您可以了解有关该主题的更多信息。