PHP -> PDO Update Statement

2019-05-30 01:51发布

问题:

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?

回答1:

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));


回答2:

You are trying to do an update, not an insert

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