简体   繁体   English

Mysql_query更新

[英]Mysql_query UPDATE

I could swear that I had this working last week, but now I get errors. 我可以发誓我上周有这个工作,但是现在我得到了错误。

In PHP I have a large CSV file that I run through a foreach loop and in this loop I have a created a variable that adds an UPDATE line to itself, like this: 在PHP中,我有一个很大的CSV文件,该文件通过foreach循环运行,并且在此循环中,我创建了一个变量,向其自身添加了UPDATE行,如下所示:

foreach ($csv->data as $value){
   $updater .= "UPDATE tblProduktData SET xtra = 2 WHERE id = '$value[1]';";
}
mysql_query("$updater") or die(mysql_error());

The CSV file contains over 3000 lines so having the mysql_query() inside the loop obviously makes the process slow and is not recommendable. CSV文件包含3000行以上的内容,因此在循环中放入mysql_query()显然会使进程变慢,因此不建议这样做。

Can anyone tell me if I'm missing something or just doing it wrong? 谁能告诉我我丢失了什么东西还是做错了?

We will temporarily ignore the fact that you are using a PHP extension mysql_ that has been deprecated ( Scheduled for removal from the language) for a number of years now. 我们将暂时忽略以下事实:您使用的PHP扩展mysql_已被弃用(已计划从语言中删除)已有很多年了。

For some reason you are adding to the sql query each time through the loop by using the .= syntax. 由于某种原因,每次使用.=语法在循环中都将添加到sql查询中。 I assume you thought you could run more than one query at a time using the mysql_ extension, but you cannot. 我认为您认为可以使用mysql_扩展名一次运行多个查询,但您不能。

So try this :- 所以试试这个:-

foreach ($csv->data as $value){
   $updater = "UPDATE tblProduktData SET xtra = 2 WHERE id = '$value[1]'";
   mysql_query($updater) or die(mysql_error());
}

This is in fact a perfect candidate for using mysqli_ or PDO prepared statements. 实际上,这是使用mysqli_或PDO预备语句的理想选择。

The mysqli_ extension manual mysqli_扩展手册

The PDO manual PDO手册

Try this: 尝试这个:

$id = "0"; // initialze the ids to update with a non-existing value
// fetch all the ids into a variable
foreach ($csv->data as $value){
  $id .= "," . $value[1] 
}

$updater .= "UPDATE tblProduktData SET xtra = 2 WHERE id in (".$id.") ;";
mysql_query("$updater") or die(mysql_error());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM