Jump to content

Recommended Posts

Hello all.

I have never used transactions before and I'm building a website right now and trying to use one. Now, the question here is do I use it right?

I have 3 tables, posts, users and users_to_posts which holds all ids (id, user_id, post_id). Now as I need to get the last insert id from database, I need to lock tables cause when two people post at the same time, it might get all mixed up. Now I use the lock tables statement first time. Anyway, all this story aside, the question. Do I use this block right?

if(isset($_SESSION['uID'], $_SESSION['username']))
        { // User
            try
            {
                $dbh->beginTransaction();
                $stmt = $dbh->exec('LOCK TABLES `posts` WRITE, `users_to_posts` WRITE');
                
                $insert = $dbh->prepare('INSERT INTO `posts` (`content`) VALUES (:content)');
                $insert->bindParam(':content', $post, PDO::PARAM_STR, 350);
                $insert->execute();
                
                $jointbl = $dbh->prepare('INSERT INTO `users_to_posts` (`user_id`, `post_id`) VALUES (:uID, :pID)');
                $jointbl->bindParam(':uID', $_SESSION['uID'], PDO::PARAM_INT, 11);
                $jointbl->bindParam(':pID', $dbh->lastInsertId(), PDO::PARAM_INT, 11);
                $jointbl->execute();
                
                $unlock = $dbh->exec('UNLOCK TABLES');
                $dbh->commit();
            }
            catch(PDOException $e)
            {
                echo $e->getMessage();
            }
        }

 

Oh, just in case. There are no errors, it works. I just want to know if it's the right way to use it.

Link to comment
https://forums.phpfreaks.com/topic/232697-php-pdo-transactions/
Share on other sites

My understanding of it is that you only really use them when you may need to roll back changes you make within MySQL if something goes wrong. From my point of view it just doesn't look like you really need to use transactions here, but then again, I'm still delving into PDO myself.

 

That said, you could simply use rollBack() in your catch if something does go wrong.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.