简体   繁体   中英

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.

 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:

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'; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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