Home  >  Article  >  Backend Development  >  One SQL statement updates multiple records

One SQL statement updates multiple records

WBOY
WBOYOriginal
2016-07-25 09:02:211403browse
Get two arrays from the form, one is to update the field data, the other is the condition array, I use id here

Source: http://www.liuhai.org/sql-set-key-case-when-then

  1. function save_category_district($parame,$id){
  2. if(!is_array($parame) || !is_array($id)) return false;
  3. $sql="UPDATE ".table.'category_district'.' SET ';
  4. foreach($parame as $key=>$val){
  5. $csql.=$key.'=CASE id';
  6. foreach($parame[$key] as $key=>$val) {
  7. $csql.=" WHEN {$id[$key]} THEN '{$val}'"; //Note that the key of the id here must be the same as the key of the data to be updated, which is the numeric key from the form
  8. }
  9. $csql.=' END,';
  10. }
  11. $sql.=rtrim($csql,','); //This step is to remove the comma after the last END
  12. $id=implode(',', $id); //id becomes a string here
  13. $sql.=" WHERE id IN ({$id})";
  14. if(!$this->mydb->query($sql)) return false;
  15. return true;
  16. }
Copy code


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:SMS platform PHP codeNext article:SMS platform PHP code