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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5055885/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 16:40:40  来源:igfitidea点击:

php run once and insert twice in mysql database

phpmysqlinsert

提问by nicng

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

回答by Endy Jasmi

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 .htaccessto 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所有内容都指向索引文件。浏览器自然会请求脚本两次,一次是针对自身的脚本,另一次是针对网站图标。

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

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

回答by amer hamdan

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->query,例如:

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

回答by Jatin Raikwar

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.

我试过你的代码在我的系统上工作。

回答by V Fedder

I had this issue happening on Chrome Browser and found 2 ways to solve it;

我在 Chrome 浏览器上遇到了这个问题,并找到了 2 种方法来解决它;

  1. You can add a captcha control on your form. This prevents it from running twice and entering that extra data line to SQL.You can get the captcha code from here;
  1. 您可以在表单上添加验证码控件。这可以防止它运行两次并将额外的数据行输入到 SQL。您可以从这里获取验证码;

click for Captcha information

点击获取验证码信息

  1. Create a session control by starting a session on your form page;

    $_SESSION['formzt']= 0;

  1. 通过在表单页面上启动会话来创建会话控件;

    $_SESSION['formzt']= 0;

And in your POST page use an "if" statement before your insert;

在您的 POST 页面中,在插入之前使用“if”语句;

if ($_SESSION['formzt']==0){

$sql="INSERT INTO members (user)
VALUES ('testini')";

if (mysqli_query($conn, $sql)) {
   echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}

  $_SESSION['formzt']++;

 }

This will prevent it from reinsert.

这将防止它重新插入。

回答by Sarwar Erfan

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 爬虫正在抓取您的页面(向 url 发送第二个 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 ...

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

回答by karmiphuc

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 的东西,Firebug 的东西,广告跟踪的东西......

回答by Rahul Singh

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

这个问题也可能是由于你可能混合了GETPOST

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.

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

回答by artoodetoo

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 服务器访问日志。

回答by Panda

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_backtracehttp: //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 Constraintto prevent duplicate rows from being inserted in the first place. Find out more at http://www.w3schools.com/sql/sql_unique.asp.

或者,您可以使用SQL UNIQUE Constraint来防止首先插入重复的行。在http://www.w3schools.com/sql/sql_unique.asp了解更多信息



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

请注意:有mysql()已被弃用,请MySQLi改用。

回答by lazek

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.

然后你可以调用你的插入页面。在每个请求中,您都可以看到正在发生的事情。