Vahik Hovsepyan Vahik Hovsepyan - 6 days ago 4x
MySQL Question

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


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