dqaxw44567 2011-02-16 20:09
浏览 149
已采纳

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?

  • 写回答

2条回答 默认 最新

  • duanhuan3705 2011-02-16 21:38
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗
  • ¥15 钢筋实图交点识别,机器视觉代码
  • ¥15 如何在Linux系统中,但是在window系统上idea里面可以正常运行?(相关搜索:jar包)
  • ¥50 400g qsfp 光模块iphy方案
  • ¥15 两块ADC0804用proteus仿真时,出现异常
  • ¥15 关于风控系统,如何去选择