Home  >  Article  >  Backend Development  >  PHP transaction processing data sample code

PHP transaction processing data sample code

怪我咯
怪我咯Original
2017-07-12 16:42:221443browse

MySQL transactions are mainly used to process data with large operations and high complexity. For example, in the personnel management system, if you delete a person, you need to delete not only the basic information of the person, but also the information related to the person, such as mailbox, articles, etc. In this way, theseDatabase OperationThe statement constitutes a transaction!

In MySQL, only databases or tables using the Innodb database engine support transactions.

Transaction processing can be used to maintain the integrity of the database and ensure that batches of SQL statements are either all executed or not executed at all.

Transactions are used to manage insert, update, delete Statements

Generally speaking, transactions must meet four conditions (ACID): Atomicity (atomicity), Consistency (Stability), Isolation (Isolation), Durability (Reliability)

1. Atomicity of transactions: A set of transactions either succeeds or is withdrawn.

2. Stability: If there is illegal data (foreign key constraints and the like), the transaction will be withdrawn.

3. Isolation: transactions run independently. If the result of one transaction affects other transactions, the other transactions will be withdrawn. 100% isolation of transactions requires sacrificing speed.

4. Reliability: After the software or hardware crashes, the InnoDB data table driver will use the log file to reconstruct and modify it. Reliability and high speed are incompatible. The innodb_flush_log_at_trx_commit option determines when to save transactions to the log.

PHP transaction processing data implementation code, friends in need can refer to it.

public function insertUser ($userArray){ 
foreach ($userArray as $key => $value) { 
@$field .= "$key,"; 
@$content .= "'$value',"; 
} 
$field = ereg_replace(',$', '', $field); 
$content = ereg_replace(',$', '', $content); 

$db = db_connect(); //连接数据库 

$db->autocommit(FALSE); //设置为非自动提交——事务处理 

$sql1 = "INSERT INTO t_user (".$field.") VALUES (".$content.")"; 
$result1 = $db->query($sql1); 

$sql2 = "INSERT INTO t_userpost (f_username) VALUES ('".$userArray['f_username']."')"; 
$result2 = $db->query($sql2); 

if ($result1 && $result2) { 
$db->commit(); //全部成功,提交执行结果 
echo '提交'; 
} else { 
$db->rollback(); //有任何错误发生,回滚并取消执行结果 
echo '回滚'; 
} 
$db->close(); 
}

The above is the detailed content of PHP transaction processing data sample code. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn