0

我在这个页面上了解到 foreach 很快,对数据库的查询不是。所以我试图做一个单一的 UPDATE 查询,但它不起作用:

$array = '';
foreach ($myar as $key => $value) {
  $array .= " (name='$value' WHERE lid='$key'), ";
}

$link1 = $db->prepare("UPDATE leyes SET $array");
$link1->execute();  

我收到一个错误:致命错误:未捕获异常 'PDOException' 并带有消息 'SQLSTATE[42000]:语法错误或访问冲突:1064 您的 SQL 语法有错误

一种解决方案:

  $array = '';

  foreach ($myarr as $key => $value) {
      $array .= " WHEN '$key' THEN '$value' ";
  }
  $array .= " ELSE name
  END";

  $link1 = $db->prepare("UPDATE table SET name = CASE id $array");
  $link1->execute();  
4

3 回答 3

0

试试喜欢

$array = '';
$i = 1;
foreach ($myar as $key => $value) {
    $array .= " name='$value' WHERE lid='$key'";
    if(count($myar) != $i++)
       $srray .= ',';
}
$link1 = $db->prepare("UPDATE leyes SET $array");
$link1->execute();  

我认为你在最后一个 Where 语句中遇到了额外的 ',' 的问题

于 2013-03-30T11:00:15.087 回答
0

只添加这一行

$array = '';
foreach ($myar as $key => $value) {
  $array .= " (name='$value' WHERE lid='$key'), ";
}

//Add this
$array = substr($array, 0, -2);

$link1 = $db->prepare("UPDATE leyes SET $array");
$link1->execute();
于 2013-03-30T11:06:15.003 回答
0

I'd never seen this sort of syntax for an UPDATE before, I had to co firm my suspicion that it wouldn't work that way. To the best of my understanding you can't use multiple WHERE clauses in an UPDATE. You can't do what you're looking for in a single statement.

That said, there are optimization strategies you can use. Start here: http://www.kavoir.com/2009/05/mysql-update-multiple-rows-with-one-single-query.html

于 2013-03-30T11:58:19.853 回答