pdo-wrapper
pdo-wrapper copied to clipboard
Update JSON column
Hi I had to work with a JSON column, so I modified your update just to work with JSON_REPLACE. I am using locally not to touch Database.php This is the function
// update JSON column function updateJSON($table, $column, $data, $where) { //collect the values from data and where $values = [];
//setup fields
$fieldDetails = null;
foreach ($data as $key => $value) {
$fieldDetails .= " $key, ?,";
$values[] = $value;
}
$fieldDetails = rtrim($fieldDetails, ',');
//setup where
$whereDetails = null;
$i = 0;
foreach ($where as $key => $value) {
$whereDetails .= $i == 0 ? "$key = ?" : " AND $key = ?";
$values[] = $value;
$i++;
}
$stmt = $this->run("UPDATE $table SET $column = JSON_REPLACE($column, $fieldDetails) WHERE $whereDetails", $values);
return $stmt->rowCount();
}
The only differences: the need of a column in the arguments and the comma instead of = in the fileDetails