dcblogdev/pdo-wrapper

Update method improved

Closed this issue · 1 comments

scano commented

If you set a where property that appers in data array, the array merge remove duplicates and the bind params throw error.
Example:

$db->update("table",["gid" => "XXXXXX", "group_gid" => "YYYYYY"],["gid" => "XXXXXX"]);

With these, $values array only have 2 items to bind so throw SQL ERROR.

Just rewrite this function like this:

public function update(string $table, array $data, array $where): int {
  //collect the values from data
  $values = array_values($data);
  
  //setup fields
  $fieldDetails = [];
  foreach ($data as $key => $value) {
	  $fieldDetails[] = "$key = ?";
  }
  $fieldDetails = implode(",", $fieldDetails);
  
  //setup where
  $whereDetails = [];
  foreach ($where as $key => $value) {
	  $whereDetails[] = "$key = ?";
	  //append values from where
	  $values[] = $value;
  }
  $whereDetails = implode(" AND ", $whereDetails);
  
  $stmt = $this->run("UPDATE $table SET $fieldDetails WHERE $whereDetails", $values);
  
  return $stmt->rowCount();
}

Thanks for your time!

the latest release fixes the update clashing