Reputation: 4055
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!';
}
}
}
Upvotes: 2
Views: 5485
Reputation: 11562
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
Upvotes: 2