Sol Sol - 3 months ago 8
PHP Question

How to update a database with PDO?

I do a

print_r($params);
and every value comes through. For some reason it isn't updating the database.

Select statements work with my other PDO statements and I can update items with mysql, but am upgrading those to PDO (such as this statement).

Is there anything wrong with my syntax?

$getData = new Data();
$gptest = $getData -> insert_group_id($item_id, $id, $gp, $groupid, $type);


Data() class includes these:

function insert_group_id($item_id, $id, $gp, $groupid, $type) {

$params = array(
'item_id' => $item_id,
'id' => $id,
'gp' => $gp,
'group_id' => $groupid,
'type' => $type
);

$qry = "UPDATE actions_item
SET gp = :gp ,
group_id = :group_id ,
type = :type
WHERE itemID = :item_id
AND itemVID = :id
";

return $this->update($qry, $params);
}

protected function update($sql, $params)
{
$stmt = $this->dbh->prepare($sql);
return $stmt->execute($params);
}

Answer

Your array keys need to have the same format as the placeholders.

$params = array(
        ':item_id' => $item_id,
        ':id' => $id,
        ':gp' => $gp,
        ':group_id' => $groupid,
        ':type' => $type
    );

Based on what I've learned since I wrote this, the colons shouldn't be required. I set up a table with all your same column names and your exact code worked for me without them. So, I'm really not sure why this seemed to solve the problem.