Page 1 of 1

PHP - Update MySQL table with data from array

Posted: 06 Apr 2015, 14:04
by PloMar
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.

PHP - Update MySQL table with data from array

Posted: 06 Apr 2015, 14:12
by Admin
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, ','));
}