如何在wordpress中使用mysql事务?

10 php mysql wordpress

如何在wordpress中使用mysql事务?我想删除10个子节点,如果有一个是活动的,则总删除将是回滚.

The*_*pha 25

我从来没有尝试过它,并没有什么额外的普通,但它只是运行一个查询(运行您的查询后START TRANSACTION使用COMMITROLLBACK取决于结果):

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
}
Run Code Online (Sandbox Code Playgroud)

因此,它可以使用类似的东西转换为wordpress

$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
}
Run Code Online (Sandbox Code Playgroud)

您也可以使用try catch这样的答案,(不是WordPress,但相同的想法).您可以在Codex上阅读有关$wpdb查询函数(querydelete)的更多信息.

MySQL的默认MyISAM存储引擎不支持事务,所以它不是一个选项.如果要使用事务,请确保将所有表定义为InnoDB.

  • 这里的问题是 truncate 有一个隐式提交:https://dev.mysql.com/doc/refman/8.0/en/truncate-table.html (3认同)