简体   繁体   English

PHP MySql update()与数组

[英]PHP MySql update() with array

I want to update my database with the help of array,how it will be right to write the code? 我想在数组的帮助下更新数据库,编写代码如何?

Here is my code but it gives error smth about MySql server version. 这是我的代码,但是它给出了有关MySql服务器版本的错误信息。

 public function update($fields, $values, $id) {
        $implodeFieldsArray = implode( ',', $fields );
        $implodeValuesArray = '"'.implode( '","', $values ).'"';
        $stmt = $this->conn->prepare('UPDATE $this->tabname ('.$implodeFieldsArray.') WHERE id=$id VALUES ('.$implodeValuesArray.')');
        $stmt->execute();
    }

According to mysql docs this is the correct syntax: 根据mysql文档,这是正确的语法:

UPDATE [LOW_PRIORITY] [IGNORE] table_reference
SET col_name1={expr1|DEFAULT} [, col_name2={expr2|DEFAULT}] ...
[WHERE where_condition]
[ORDER BY ...]
[LIMIT row_count]

Your code will become: 您的代码将变为:

public function update($fields, $values, $id) {
    $update = "";
    $update = "";
    for ($i=0;$i<count($fields)-1;$i++){
      $update .= $fields[$i]."='".$values[$i]."',";
    }
    $update .= $fields[$i]."='".$values[$i]."'";
    $sql = 'UPDATE '.$this->tabname.' SET '.$update.' WHERE id='.$id;
    $stmt = $this->conn->prepare($sql);
    $stmt->execute();
}

Use following syntax for updates 使用以下语法进行更新

UPDATE `tablename`
SET `column1`='new column1 value', `column2`='new column2 value'
WHERE `somecolumn`='some value'; 

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

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