php run once and insert twice in mysql database

I'm facing the same issue as you, the problem only occus when I use Opera or chrome.

For my case, I have an .htaccess to point every thing to the index file. Naturally the browser will request the script twice, once for the script it self, the other is for the favicon.

The fix: Try to edit the .htaccess to prevent redirection to the index file when the browser is requesting for favicon.ico


Do you see this

$result = $db->query($query);

And the next line:

if ($db->query($query) === TRUE) {

This means that you run your query twice. Remove one of the $db->query, e.g.:

$result = $db->query($query);
if ($result === TRUE) {    /* do stuff */

Code is fine.

Try to change browser. If still not worked.

Restart server Still not

Try to write in another file outside of project as single script.

It will work.

I tried your code its working on my system.


As you mentioned the problem does not occur when you test locally, only occurs when you deploy in server --- I guess you have Google Adsense in your page. In that case, adsense crawler is crawling your page (sending the second http request to the url)

To avoid this, add following in start of your php file:

if(strpos($_SERVER['HTTP_USER_AGENT'],'Mediapartners-Google') !== false) {
        exit();
}

I had faced similar issue in a script which sends emails. I was getting double emails per action :(

Then, I investigated into the server access log, and discovered the second request per action from this user agent ...