Reputation: 10649
In my script, I insert some data to mysql:
$query = "INSERT INTO recent_queries (`type`, `fetched`, `expires`) VALUES ('$type', '$fetched', '$expires')";
$mysqli->query($query);
It works fine. One new row is added to the database. Each time I refresh the page, one more row is added. However, if I copy the URL, open a new tab, paste the URL in the address bar and go to the page, TWO new rows are added.
Sometimes I have noted three or four rows being added for one page load, but it has been hard to pinpoint when exactly this happens. With the opening of the new tab, it always inserts two new rows, so that was easy to pinpoint.
Why might the page be loaded more than once, and how can I prevent this from occurring?
Upvotes: 0
Views: 185
Reputation: 1743
Normally isset($_POST) is used to avoid such scenarios, you could also try creating a variable
$affectedRows = $mysqli->affected_rows;
Store the value in session variable or something, Or another long way is Create a temp txt file and check if file_exists everytime before insert. if($affectedRows > 0 )
{
//Do what you want to do
}else
{
Reinsert the Data
}
Upvotes: 0
Reputation: 1640
Any time an HTTP request alters information on the server it should be a POST, PUT or DELETE (usually POST). This is how this problem is normally avoided.
You may also want to look into PDO to avoid SQL injection attacks.
Upvotes: 2