php mysql同时写入数据库表,MYSQL,PHP插入到数据库中的多个表中

I'm trying to insert information into multiple tables within a database, i have managed to get it to work using this:

$query = "INSERT INTO users (grp, email, college_id, tutor, year, password, register_date) VALUES ('$g', '$e', '$ci', '$tu', '$y', PASSWORD('$p'), NOW() )";

$query2 = "INSERT INTO unit_26 (college_id) VALUES ('$ci')";

$result = mysql_query ($query); // Run the Query Now woooo.

$result2 = mysql_query ($query2); // Run the Query Now woooo.

if ($result) { // If it Ran OK.

Although it works and the information is added to both tables, I was just wondering if anyone has a better way of doing this, or of this way is wrong?

Thanks

解决方案

Since these two inserts are executed independently, another program running concurrently might see the database in a state where the first insert is done but the second isn't.

Whether this is a problem or not depends on the application logic. In your case it's hard to tell without additional information. Probably not. A financial transactions involving two accounts is an example where this is a problem: you don't want the sum of all account balances to be wrong at any time.

If you think you need this, you can make the operation atomic at the cost of performance: another program will either see the database before the first insert, or after the second insert. It works like this:

$result = FALSE;

if (mysql_query('BEGIN')) {

if (mysql_query($query1) &&

mysql_query($query2))

$result = mysql_query('COMMIT'); // both queries looked OK, save

else

mysql_query('ROLLBACK'); // problems with queries, no changes

}

The storage engine has to support transactions, i.e., it has to be InnoDB. Otherwise this will silently not work.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值