Reputation:
I need to do 2 query.
Basically it's a
mysql_query("INSERT INTO table ($value1,$value2)");
and
mysql_query("UPDATE table2 SET field1 = '$value1', field2 = '$value2'");
I think I can simply do a
if (mysql_query("INSERT ...") !== false) {
mysql_query("UPDATE ...");
}
In this case should I use a transaction? And how should I use it?
Or can i leave that simple if?
Thanks
Upvotes: 0
Views: 4128
Reputation: 9
For insert and updates MySQL has a good, alternative solution - "ON DUPLICATE KEY UPDATE". It does what you want safely in a single query:
INSERT .... ON DUPLICATE KEY UPDATE
(also the key must be set as unique in this scenario)
http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
Upvotes: 0
Reputation: 401182
You will generally use transactions if you want some "all or nothing" behavior.
Basically, with transactions, you can :
If working with mysql_*
function, you'll have to :
START TRANSACTION
queryCOMMIT
or a ROLLBACK
query.To detect whether a query succeeded or not, you can indeed check the return value of mysql_query()
: it will return false
in case of an error.
Note : MySQL is the old extension -- and doesn't have functions to deal with transactions ; which means you have to deal with them as regular queries.
Working with MySQLi, you could use :
mysqli::autocommit()
to disable autocommitmysqli::commit()
or mysqli::rollback()
Upvotes: 2