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

Merge in update() method will omit data

Open superthin opened this issue 5 years ago • 1 comments

Line 179 - 183:

`       //merge data and where together
        $collection = array_merge($data, $where);

         //collect the values from collection
        $values = array_values($collection);`

Merge array $data and $where if they have same columns -> lost data.

The problem will occur when we want to update a column which appear in where (or in array $values). Eg.:

UPDATE contact SET phone = '012-345-6789', first_name='Patrick' WHERE phone = 012-345-9950';

How to solve the problem?

superthin avatar Nov 12 '20 06:11 superthin

Hi,

Did you resolve this issue?

ejayfl avatar Aug 25 '21 19:08 ejayfl

Bit of an old issue, but updating the 'update' function should resolve this...

    public function update($table, $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 $fieldDetails WHERE $whereDetails", $values);
        
        return $stmt->rowCount();
    }

DizzySquirrel avatar Nov 25 '22 17:11 DizzySquirrel

Do you want to open a pull request? I'm without my laptop for a few days

dcblogdev avatar Nov 25 '22 19:11 dcblogdev