Skip to content

Update JSON column #22

@nelson906

Description

@nelson906

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions