Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
598 views
in Technique[技术] by (71.8m points)

php - How to use mysql transaction in wordpress?

How to use mysql transaction in wordpress? I want delete 10 child, if one is active, the total delete will be rollback.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I've never tried it and there is nothing extra ordinary but it's just about running a query like (Run your queries after START TRANSACTION and use COMMIT or ROLLBACK depending on the result) :

mysql_query('START TRANSACTION');
$res1 = mysql_query('query1');
$res2 = mysql_query('query2');
If ( $res1 && $res2 ) {
    mysql_query('COMMIT'); // commits all queries
} else {
    mysql_query('ROLLBACK'); // rollbacks everything
}

So, it could be converted to wordpress, using something like this

$wpdb->query('START TRANSACTION');
$result1 = $wpdb->delete( $table, $where, $where_format = null );
$resul2 = $wpdb->delete( $table, $where, $where_format = null );
if($result1 && $result2) {
    $wpdb->query('COMMIT'); // if you come here then well done
}
else {
    $wpdb->query('ROLLBACK'); // // something went wrong, Rollback
}

You may also use try catch like this answer, (not WordPress but same idea). You can read more about $wpdb query functions (query and delete) on Codex.

MySQL’s default MyISAM storage engine does not support transactions, so it’s not an option. If you want to use transactions, ensure all your tables are defined as InnoDB.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...