Home > Database > Mysql Tutorial > Why Do I Get Two Entries in My MySQL Database When I Only Insert Once in PHP?

Why Do I Get Two Entries in My MySQL Database When I Only Insert Once in PHP?

DDD
Release: 2024-12-03 01:49:10
Original
950 people have browsed it

Why Do I Get Two Entries in My MySQL Database When I Only Insert Once in PHP?

Why Does Inserting Once in PHP Cause Two Entries in MySQL Database?

When executing the provided PHP code on a server, you may encounter a perplexing issue where inserting a single record into a MySQL database results in two entries. This problem, which manifests when the code is deployed on a live server but not on localhost, has been baffling developers.

The culprit behind this anomaly lies in the browser's behavior. Upon refreshing the page, the browser sends two requests to the server: one for the main script and another for the favicon. In this situation, the insert query is executed twice, leading to the insertion of two records.

To resolve this issue, the insert query should be restricted to only one of the requests. By implementing a conditional check that verifies whether the request is for the main script, you can prevent the query from being executed for the favicon request.

Here's a modified code snippet that addresses this issue:

<?php
$db = mysql_connect('localhost', 'zzzzzzz', 'xxxxxx') or die('Unable to connect.' . mysql_error());
mysql_select_db('test', $db) or die(mysql_error($db));

// Check if the request is for the main script
if ($_SERVER['REQUEST_URI'] == '/script.php') {
    $sql = "INSERT INTO test_table(value, insert_time) VALUES ('testing', '" . time() . "')";
    $result = mysql_query($sql);
}

$select = "select * from test_table";
$rs = mysql_query($select);
while ($row = mysql_fetch_array($rs)) {
    echo $row["test_id"] . " -- " . $row["value"] . " -- " . $row["insert_time"] . "<br />";
}
?>
Copy after login

By incorporating this conditional check, the insert query is only executed when the main script is requested, ensuring that only a single record is inserted into the database.

The above is the detailed content of Why Do I Get Two Entries in My MySQL Database When I Only Insert Once in PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template