pdo-wrapper icon indicating copy to clipboard operation
pdo-wrapper copied to clipboard

Update JSON column

Open nelson906 opened this issue 1 year ago • 1 comments

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

nelson906 avatar May 22 '24 17:05 nelson906

I forgot the data format $data = [ '$.employer.firstName' => 'Joe', '$.employer.lastnName' => 'Smith', '$.employer.email' => '[email protected]' ]; $where = ['id' => 2]; $db->update('users', $column, $data, $where);

nelson906 avatar May 22 '24 18:05 nelson906