2

Im currently following a tutorial on creating a forum in PHP / MySQL ... and im trying to implement it into my CodeIgniter project.

I have hit a snag that i have never dealt with before, transactions ... I have read the documentation on codeigniters transactions, but im not really understanding it considering the code i need to convert.

I was wondering if someone could take the code below and turn it into codeigniters transaction code for me, i have tried doing it myself but its using multiple tables and i just get completely confused.

Any help would be great, code is below:

$query = "BEGIN WORK;";
$result = mysql_query($query)

if(!$result) {
    echo 'An error has occured';
} else {
    $sql = "INSERT INTO topics(t_subeject,date,cat) VALUES ($_POST['subject'],NOW(),$_POST['cat'])";
    $result = mysql_query($sql);

    if(!$result) {
        echo 'An error has occured';
        $sql = "ROLLBACK;";
        $result = mysql_query($query)
    } else {
        $topid = mysql_insery_id();
        $sql = "INSERT INTO posts(content, date) VALUES ($_POST['content'],NOW())";
        $result = mysql_query($sql);

        if(!$result) {
            echo 'An error has occured';
            $sql = "ROLLBACK;";
            $result = mysql_query($sql);
        } else {
            $sql = "COMMIT;";
            $result = mysql_query($sql);
            echo 'Insert successful!';
        }
    }
}

1 Answer 1

2

If an INSERT failed, it will do a ROLLBACK automatically. That's why you're using transactions in the first place. No need to explicitly check for it. So in the end, this should be all there is to it:

$this->db->trans_start();
$this->db->query("INSERT INTO topics(t_subeject,date,cat) VALUES ($_POST['subject'],NOW(),$_POST['cat'])");
$topid=$this->db->insert_id();
$this->db->query("INSERT INTO posts(content, date) VALUES ($_POST['content'],NOW())");
$this->db->trans_complete();

...from within your model class. So if the first INSERT already fails, it won't execute the second.

http://ellislab.com/codeigniter/user_guide/database/transactions.html

Sign up to request clarification or add additional context in comments.

3 Comments

Hey, thanks for that .. that makes things a little easier, after the first query, how would i go about getting the mysql_insert_id, also if the first query fails will it still run the second one?
You're welcome. And make sure your table engine supports transactions. MyISAM does not, InnoDB does.
haha yeh i found that out the hard way, took me a few hours of staring at the screen hehe

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.