Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does my PHP transaction not work?

Tags:

php

mysql

pdo

I'm working on a school project creating a CMS for my portfolio site. I am having trouble getting my update function to work. I have a feeling it has something to do with the way I'm constructing my PDO Transaction. In my database I have a projects table, category table, and the associative content_category table. I'm able to insert my projects into those tables just fine. What I want to do is insert into my projects table then delete all records from the content_category table and finally insert the current category records into that associative table to complete the transaction. I do get my return statement "Project Updated" returned. But the tables aren't being updated. Any ideas anyone?

Here's the code:

This is a function in my Project class.

public function update(){
    try {
        $conn = getConnection();
        $conn->beginTransaction();
        $sql = "UPDATE project 
                SET project_title = :title, 
                    project_description = :desc, 
                    project_isFeatured = :feat, 
                    project_mainImage = :image
                WHERE project_id = :id";
        $st = $conn->prepare($sql);
        $st->bindValue(":id", $this->id, PDO::PARAM_INT);
        $st->bindValue(":title", $this->title, PDO::PARAM_STR);
        $st->bindValue(":desc", $this->description, PDO::PARAM_STR);
        $st->bindValue(":feat", $this->isFeatured, PDO::PARAM_BOOL);            
        $st->bindValue(":image", $this->mainImage, PDO::PARAM_INT);
        $st->execute(); 

        $sql = "DELETE from content_category
                WHERE content_id = :id";
        $st = $conn->prepare($sql);
        $st->bindValue("id", $this->id, PDO::PARAM_INT);
        $st->execute();

        $sql = "INSERT into content_category (content_id, cat_id)
                VALUES (?,?)";
        $st = $conn->prepare($sql);

        foreach($this->categories as $key=>$value){
            $st->execute(array(intval($projectID), intval($value)));                                        
        }
        $conn->commit();
        $conn = null;
        return "Project updated";                   
    }
    catch(Exception $e) {
        echo $e->getMessage();
        $conn->rollBack();
        return "Error... Unable to update!";
    }
}
like image 876
Joel R. Avatar asked Dec 22 '22 00:12

Joel R.


1 Answers

Your database engine for the tables needs to be INNODB. If you are using phpMyAdmin, it defaults to MyISAM. (I don't know if that will cause the updates not to go through or just the transaction line to be ignored. Edit: Pretty sure the documentation is saying that it will throw an error and not do anything if you beginTransaction on a myISAM)

like image 105
phpmeh Avatar answered Dec 24 '22 03:12

phpmeh