简体   繁体   中英

MYSQL, PHP Insert into Multiple Tables in Database

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?

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, ie, it has to be InnoDB . Otherwise this will silently not work.

SQL inserts are for a single table only. You can't insert data into two or more tables at the same time with a single INSERT query. You can force the separate insertions to be atomic by using a transaction, but you still have to do an INSERT for each table.

Might be nice if you could so something like

INSERT INTO t1.id, t2.val, t3.other VALUES ($t1id, $t2val, $t3other);

but alas...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM