junjie
junjie

Reputation: 11

PHP -> PDO Update Statement

I was trying to do a SQL query ( insert into users set cash = cash + 20 ), can anyone help me with the PDO prepared statement version of the above query?

Upvotes: 1

Views: 7122

Answers (2)

Francois Deschenes
Francois Deschenes

Reputation: 24969

I can't really figure out if you're looking to insert or update. Here are PDO prepared statement examples. They assume that you've already connected and that the PDO object is $dbh.

Insert:

$sth = $dbh->prepare('INSERT INTO `users` (`cash`) VALUES (?)');
$sth->execute(array(20));

Update:

// All users
$sth = $dbh->prepare('UPDATE `users` SET `cash` = `cash` + ?');
$sth->execute(array(20));

// A specific user (assuming that there's a field name "id")
$sth = $dbh->prepare('UPDATE `users` SET `cash` = `cash` + ? WHERE `id` = ?');
$sth->execute(array(20, $id));

Upvotes: 3

Ibu
Ibu

Reputation: 43810

You are trying to do an update, not an insert

 UPDATE users SET cash = (cash + 20)
 WHERE <condition>

Upvotes: 0

Related Questions