0

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'];
} 
Liam
  • 9,725
  • 39
  • 111
  • 209

2 Answers2

1

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.

PHP + MySQL transactions examples

Community
  • 1
  • 1
Jose Vega
  • 10,128
  • 7
  • 40
  • 57
  • Thanks @JoseVega I think thats all I'm confused about, whether or not it could all be done in 1 query – Liam May 30 '13 at 13:07
1

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.

Vlad Preda
  • 9,780
  • 7
  • 36
  • 63