多个if与单独的数据库查询

时间:2017-06-09 16:38:55

标签: php mysql if-statement

1.  $sql = "UPDATE table_name SET";
2.
3.  foreach($array as $key => $val){
4.      if($key == 'abc')
5.          $val = 'test';
6.      $sql .= $key . " = '" . $val . "' ";
7.  }
8.
9.  $sql .= "WHERE primary_key = 2";

更好地检查foreach循环中的值(第4-5行)?或者运行单独的更新查询?

OR

1.  $sql = "UPDATE table_name SET";
2.
3.  foreach($array as $key => $val){
4.      $sql .= $key . " = '" . $val . "' ";
5.  }
6.
7.  $sql .= "WHERE primary_key = 2";
8.  
9.  $sql = "UPDATE table_name SET abc = 'test'";

*这是一个通用的例子,请忽略错字并提前感谢。

1 个答案:

答案 0 :(得分:0)

1.  $sql = "UPDATE table_name SET";
2.
3.  if( isset($array['abc']) ){
4.      $array['abc'] = 'test';
5.  }
6.
7.  foreach($array as $key => $val){
8.      $sql .= $key . " = '" . $val . "', ";
9.  }
10.
11.  $sql = substr($sql, 0, -2);
12.  $sql .= " WHERE primary_key = 2";

谢谢@u_mulder。