PHP - Update MySQL table with data from array

Discuss coding issues, and scripts related to PHP and MySQL.
PloMar
Posts: 48

PHP - Update MySQL table with data from array

Hello,
I have the following method to update data in MySQL table.

Code: Select all

public function update($table, $rows){
  foreach($rows as $k => $v) {
    $sql = "UPDATE $table SET $k='$v'";
  }
  $this->query($sql);
}

I use this code to call the update() method:

Code: Select all

require_once 'db.php';
$db = new db;
$db->update('admin', ['password'=>'test','email'=>'test']);
When I apply: var_dump($sql); i get this result:

Code: Select all

$sql = "UPDATE admin SET email='test'";
How to change the method to add all data from the array $rows in the $sql string, so to result this SQL query?

Code: Select all

$sql = "UPDATE admin SET password='test', email='test'";
Thanks.

Admin Posts: 805
Hi,
Try this code:

Code: Select all

public function update($table, $rows){
  $set = [];
  foreach($rows as $k => $v) {
    $set[] = "$k='$v'";
  }
  $sql = "UPDATE $table SET ". implode(', ', $set);
  $this->query($sql);
} 
Or this:

Code: Select all

public function update($table, $rows){
  $sql = "UPDATE $table SET ";
  foreach($rows as $k => $v) {
    $sql .= " $k='$v',";
  }
  $this->query(trim($sql, ','));
}