Im trying to figure out how to update my table using PDO - I need to update 2 records simultaneously only im unsure how this works.
I have my session user, and my "befriended user".
My befriended user will have 10 credits or so in my table and he can offer other users X credits when they befriend him.
// $uid is my logged in session user
// $follow_id is the id of the person were trying to befriend
// Im confused by the whole process of this do i write 2 queries? 1 that minuses credits from the befirended user, and then one that adds the credits to the current session users column?
$upd_stmt = $conn->prepare('SELECT * FROM users WHERE user_id=? ');
$upd_stmt->bindParam(1, $uid, PDO::PARAM_INT);
$upd_stmt->execute();
while( $row = $upd_stmt->fetch(PDO::FETCH_ASSOC) ) {
$row['credits_offered'];
}
The short answer is, yes, you will need to write two queries, one to subtract and the other to add.
You could probably do it in one query, but I would recommend doing it in two for better readability. I would also recommend doing it via a transaction, if the first query executes successfully but the second doesn't, you would want to roll it back.
This is what transactions were made for. You don't need to do this in one query to make sure they are both executed succefully.
$dbh->beginTransaction();
$addQuery = "UPDATE ...";
$subtractQuery = "UPDATE ...";
$sth = $dbh->exec($addQuery);
$sth = $dbh->exec($subtractQuery);
$dbh->commit(); // or $dbh->rollback();
Read more about transactions here: http://en.wikipedia.org/wiki/Database_transaction
Short version - they ensure that either all your queries are executed succefully, or none.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.