php运行一次并在mysql数据库中插入两次

时间:2022-07-16 01:14:40

I've got a simple code below. After it's run once, it inserts results twice into the mysql database.

我在下面有一个简单的代码。运行一次后,它会将结果两次插入mysql数据库。

if it run twice or request twice base on 1 refresh on the page, why the output is just 1 result?

如果它在页面上的1次刷新时运行两次或请求两次,为什么输出只是1个结果?

I have been googling for the whole day and struggling to resolve this issue. However, I failed to figure out what is wrong with this code. The code runs perfectly on localhost, but after it's moved to the server, the problem pops up. Has anyone faced something like this before? How can this problem be resolved?

我一直在谷歌上搜索,并努力解决这个问题。但是,我没有弄清楚这段代码有什么问题。代码在localhost上运行完美,但在将其移动到服务器后,问题会弹出。以前有人遇到过这样的事吗?如何解决这个问题?

FULL CODE:

完整代码:

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

$sql="INSERT INTO test_table(value,insert_time) VALUES ('testing','".time()."')";
$result=mysql_query($sql);
echo "result=".$result;

$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 />";
}
?>

RESULT:
result=1
1 -- testing -- 1298185509

结果:结果= 1 1 - 测试 - 1298185509

BUT IN DATABASE:
test_id , value , insert_time
1 , testing , 1298185509
2 , testing , 1298185511

但是在数据库中:test_id,value,insert_time 1,testing,1298185509 2,testing,1298185511

12 个解决方案

#1


13  

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

我和你一样面临同样的问题,当我使用Opera或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.

对于我的情况,我有一个.htaccess指向索引文件的每一件事。当然,浏览器会请求脚本两次,一次是脚本,另一次是针对favicon。

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

修复:尝试编辑.htaccess以防止在浏览器请求favicon.ico时重定向到索引文件

#2


2  

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.:

这意味着您运行查询两次。删除其中一个$ db->查询,例如:

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

#3


1  

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)

正如您所提到的,当您在本地测试时不会出现问题,只有在您在服务器中部署时才会出现 - 我猜您的页面中有Google Adsense。在这种情况下,adsense抓取工具正在抓取您的网页(将第二个http请求发送到网址)

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

要避免这种情况,请在php文件的开头添加以下内容:

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 ...

然后,我调查了服务器访问日志,并从该用户代理发现了每个操作的第二个请求......

#4


1  

This problem may also be arising due to you may be mixing the GET and POST

由于您可能混合了GET和POST,因此也可能出现此问题

Or

要么

you may have downloaded online template which is may be making an background ajax call before the page is submitted.

您可能已经下载了在线模板,该模板可能是在提交页面之前进行后台ajax调用。

Please have a look and if you find a solution or if there is any other problem let us know.

请查看,如果您找到解决方案或有任何其他问题,请告诉我们。

#5


1  

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.

我尝试将你的代码用于我的系统。

#6


0  

Ok, I know that this doesn't make any sense, but I solved removing $.ajax({async:true}); from my js file.

好的,我知道这没有任何意义,但我解决了删除$ .ajax({async:true});来自我的js文件。

#7


0  

I had the same issue on my site. After debugging I found the root cause. It is Yandex Metrica js library. It calls ajax request to the same page to calculate loading time and some other params.

我在我的网站上遇到了同样的问题。调试后我发现了根本原因。这是Yandex Metrica js图书馆。它调用ajax请求到同一页面来计算加载时间和其他一些参数。

Do you use it? If not open chrome dev panel and look at http request. May be it is request for favicon or etc.

你用它吗?如果没有打开chrome dev面板并查看http请求。可能是对favicon等的要求

#8


0  

There're many reasons to cause this, so I would suggest you using the best practice:

导致这种情况的原因有很多,所以我建议您使用最佳实践:

If you're creating a new record in your DB, you should init the logic with a POST request.

如果要在数据库中创建新记录,则应使用POST请求初始化逻辑。

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // …
}

The non-code problems should be easily avoided now: .htaccess thing, Firebug thing, ads tracking thing...

现在应该很容易避免非代码问题:.htaccess thing,Firebug的东西,广告跟踪的东西......

#9


0  

There is no problem with your code.Firebug or similar tools can make double request sometimes. Also metric scripts (yandex metrica, chartbeat etc) in your page can do same behavior. You should inspect these situations.

您的代码没有问题.Firebug或类似的工具有时会发出双重请求。您页面中的度量标准脚本(yandex metrica,chartbeat等)也可以执行相同的操作。你应该检查这些情况。

To debug it you can log insert requests, and you can inspect it to find what is wrong.

要调试它,您可以记录插入请求,您可以检查它以查找错误。

If you are using linux environment ;

如果你使用的是linux环境;

Add a log line to your code :

在代码中添加日志行:

error_log(print_r($_SERVER,true));

Open a console window and type (log directory depends on your sever configuration)

打开控制台窗口并键入(日志目录取决于您的服务器配置)

tail -f /var/log/apache/error.log

And then you can call your insert page. At every request you can see what is happening.

然后你可以调用你的插入页面。在每一个请求,你都可以看到发生了什么。

#10


0  

I guess this code from index.php which is front-controller for all requests.
When browser fetches page it usually trying to get favicon.ico too. And if favicon is missing, second request is processed your php file again. You can examine this supposition by writing $_SESSION['REQUEST_URI'] to DB.

我想这个来自index.php的代码是所有请求的前端控制器。当浏览器抓取页面时,它通常也试图获取favicon.ico。如果缺少favicon,第二个请求将再次处理您的php文件。您可以通过将$ _SESSION ['REQUEST_URI']写入DB来检查此假设。

I recommend do not change data in GET requests and research web server access log from time to time.

我建议不要随时更改GET请求和研究Web服务器访问日志中的数据。

#11


0  

Your code seems fine, and it should be probably due to external plugins that you are using, which send a 2nd request each time.

你的代码似乎很好,它可能是由于你正在使用的外部插件,每次发送第二个请求。


If you are using Google Chrome, it would most likely be due to this bug, https://bugs.chromium.org/p/chromium/issues/detail?id=123121. This bug causes Chrome to redirect every request into index.php, so the PHP script will run twice.

如果您使用的是谷歌浏览器,则很可能是由于此错误,https://bugs.chromium.org/p/chromium/issues/detail?id = 123121。此错误导致Chrome将每个请求重定向到index.php,因此PHP脚本将运行两次。

This can be fixed using the following code, as according to website.

根据网站的说法,可以使用以下代码修复此问题。

RewriteBase /
RewriteCond %{REQUEST_FILENAME} !favicon.ico
RewriteRule .* index.php [L]

You can also debug using debug_print_backtrace: http://php.net/debug_print_backtrace.

您还可以使用debug_print_backtrace进行调试:http://php.net/debug_print_backtrace。

debug_print_backtrace() prints a PHP backtrace. It prints the function calls, included/required files and eval()ed stuff.

debug_print_backtrace()打印PHP回溯。它打印函数调用,包含/必需文件和eval()ed东西。


Alternatively, you can use SQL UNIQUE Constraint to prevent duplicate rows from being inserted in the first place. Find out more at http://www.w3schools.com/sql/sql_unique.asp.

或者,您可以使用SQL UNIQUE Con​​straint来防止首先插入重复的行。有关详细信息,请访问http://www.w3schools.com/sql/sql_unique.asp。


Just a note: There are mysql() have been deprecated, use MySQLi instead.

只是注意:有mysql()已被弃用,而是使用MySQLi。

#12


-2  

$result=mysql_query($sql); echo "result=".$result;

It's because you run mysql_query($sql) twice. Try it without echo the $result.

这是因为你运行mysql_query($ sql)两次。尝试它而不回应$ result。

#1


13  

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

我和你一样面临同样的问题,当我使用Opera或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.

对于我的情况,我有一个.htaccess指向索引文件的每一件事。当然,浏览器会请求脚本两次,一次是脚本,另一次是针对favicon。

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

修复:尝试编辑.htaccess以防止在浏览器请求favicon.ico时重定向到索引文件

#2


2  

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.:

这意味着您运行查询两次。删除其中一个$ db->查询,例如:

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

#3


1  

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)

正如您所提到的,当您在本地测试时不会出现问题,只有在您在服务器中部署时才会出现 - 我猜您的页面中有Google Adsense。在这种情况下,adsense抓取工具正在抓取您的网页(将第二个http请求发送到网址)

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

要避免这种情况,请在php文件的开头添加以下内容:

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 ...

然后,我调查了服务器访问日志,并从该用户代理发现了每个操作的第二个请求......

#4


1  

This problem may also be arising due to you may be mixing the GET and POST

由于您可能混合了GET和POST,因此也可能出现此问题

Or

要么

you may have downloaded online template which is may be making an background ajax call before the page is submitted.

您可能已经下载了在线模板,该模板可能是在提交页面之前进行后台ajax调用。

Please have a look and if you find a solution or if there is any other problem let us know.

请查看,如果您找到解决方案或有任何其他问题,请告诉我们。

#5


1  

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.

我尝试将你的代码用于我的系统。

#6


0  

Ok, I know that this doesn't make any sense, but I solved removing $.ajax({async:true}); from my js file.

好的,我知道这没有任何意义,但我解决了删除$ .ajax({async:true});来自我的js文件。

#7


0  

I had the same issue on my site. After debugging I found the root cause. It is Yandex Metrica js library. It calls ajax request to the same page to calculate loading time and some other params.

我在我的网站上遇到了同样的问题。调试后我发现了根本原因。这是Yandex Metrica js图书馆。它调用ajax请求到同一页面来计算加载时间和其他一些参数。

Do you use it? If not open chrome dev panel and look at http request. May be it is request for favicon or etc.

你用它吗?如果没有打开chrome dev面板并查看http请求。可能是对favicon等的要求

#8


0  

There're many reasons to cause this, so I would suggest you using the best practice:

导致这种情况的原因有很多,所以我建议您使用最佳实践:

If you're creating a new record in your DB, you should init the logic with a POST request.

如果要在数据库中创建新记录,则应使用POST请求初始化逻辑。

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // …
}

The non-code problems should be easily avoided now: .htaccess thing, Firebug thing, ads tracking thing...

现在应该很容易避免非代码问题:.htaccess thing,Firebug的东西,广告跟踪的东西......

#9


0  

There is no problem with your code.Firebug or similar tools can make double request sometimes. Also metric scripts (yandex metrica, chartbeat etc) in your page can do same behavior. You should inspect these situations.

您的代码没有问题.Firebug或类似的工具有时会发出双重请求。您页面中的度量标准脚本(yandex metrica,chartbeat等)也可以执行相同的操作。你应该检查这些情况。

To debug it you can log insert requests, and you can inspect it to find what is wrong.

要调试它,您可以记录插入请求,您可以检查它以查找错误。

If you are using linux environment ;

如果你使用的是linux环境;

Add a log line to your code :

在代码中添加日志行:

error_log(print_r($_SERVER,true));

Open a console window and type (log directory depends on your sever configuration)

打开控制台窗口并键入(日志目录取决于您的服务器配置)

tail -f /var/log/apache/error.log

And then you can call your insert page. At every request you can see what is happening.

然后你可以调用你的插入页面。在每一个请求,你都可以看到发生了什么。

#10


0  

I guess this code from index.php which is front-controller for all requests.
When browser fetches page it usually trying to get favicon.ico too. And if favicon is missing, second request is processed your php file again. You can examine this supposition by writing $_SESSION['REQUEST_URI'] to DB.

我想这个来自index.php的代码是所有请求的前端控制器。当浏览器抓取页面时,它通常也试图获取favicon.ico。如果缺少favicon,第二个请求将再次处理您的php文件。您可以通过将$ _SESSION ['REQUEST_URI']写入DB来检查此假设。

I recommend do not change data in GET requests and research web server access log from time to time.

我建议不要随时更改GET请求和研究Web服务器访问日志中的数据。

#11


0  

Your code seems fine, and it should be probably due to external plugins that you are using, which send a 2nd request each time.

你的代码似乎很好,它可能是由于你正在使用的外部插件,每次发送第二个请求。


If you are using Google Chrome, it would most likely be due to this bug, https://bugs.chromium.org/p/chromium/issues/detail?id=123121. This bug causes Chrome to redirect every request into index.php, so the PHP script will run twice.

如果您使用的是谷歌浏览器,则很可能是由于此错误,https://bugs.chromium.org/p/chromium/issues/detail?id = 123121。此错误导致Chrome将每个请求重定向到index.php,因此PHP脚本将运行两次。

This can be fixed using the following code, as according to website.

根据网站的说法,可以使用以下代码修复此问题。

RewriteBase /
RewriteCond %{REQUEST_FILENAME} !favicon.ico
RewriteRule .* index.php [L]

You can also debug using debug_print_backtrace: http://php.net/debug_print_backtrace.

您还可以使用debug_print_backtrace进行调试:http://php.net/debug_print_backtrace。

debug_print_backtrace() prints a PHP backtrace. It prints the function calls, included/required files and eval()ed stuff.

debug_print_backtrace()打印PHP回溯。它打印函数调用,包含/必需文件和eval()ed东西。


Alternatively, you can use SQL UNIQUE Constraint to prevent duplicate rows from being inserted in the first place. Find out more at http://www.w3schools.com/sql/sql_unique.asp.

或者,您可以使用SQL UNIQUE Con​​straint来防止首先插入重复的行。有关详细信息,请访问http://www.w3schools.com/sql/sql_unique.asp。


Just a note: There are mysql() have been deprecated, use MySQLi instead.

只是注意:有mysql()已被弃用,而是使用MySQLi。

#12


-2  

$result=mysql_query($sql); echo "result=".$result;

It's because you run mysql_query($sql) twice. Try it without echo the $result.

这是因为你运行mysql_query($ sql)两次。尝试它而不回应$ result。