0

How to insert data into two or more tables?

Currently I am using this trick. (Let just assume that the syntax is correct)

$Sql1 = "insert into user";
$Sql2 = "insert into files";
$Sql3 = "insert into messages";

query $Sql1
query $$ql2
query $Sql3

So I am using this and I need to optimize.

Also, I think I need to use Foreign key? But I don't know how to do it on phpmyadmin.

and lastly:

This is all I want.

To insert data on the "user" table and then automatically the table "messages" and "files" will have also an ID which is the same with the user.. That is why I use to 3 queries in my code.

Please help me.

Thanks in ADVANCE!

myb

1
  • 3
    Why do you need to optimize this? Are the three queries posing an actual performance problem? Commented Sep 19, 2011 at 10:46

3 Answers 3

3

It is perfectly fine to use multiple queries.

However, you should wrap the 3 queries into one transaction. That is, if one query fails for some reason, the effects of all previous queries (if any) can be rolled back so that your database stays in a consistent state.

Note: Transactions are not possible with MySQL's MyISAM tables. Additionally you have to use PHP's Mysqli (or PDO) to be able to use transactions. (I assume that you're not using some high-level data base abstraction layer.)

As to your question regarding foreign keys: As far as I know, it makes no difference when you're using the MyISAM engine for the tables in your database (which I presume), because MyISAM doesn't even support the explicit modeling of foreign keys. Other table engines like InnoDB, however, can use foreign keys to check certain constraints like "a message must always be associated with an existing person".

Here are some nice examples regarding foreign keys: http://www.postgresql.org/files/documentation/books/aw_pgsql/node131.html

Sign up to request clarification or add additional context in comments.

Comments

1

This is the answer, I think : http://dev.mysql.com/doc/refman/5.1/en/example-foreign-keys.html

Comments

1

With mysql u can use LAST_INSERT_ID() or in php mysql_insert_id() function. Checkout this manual entries:

http://dev.mysql.com/doc/refman/5.0/en/getting-unique-id.html

http://php.net/manual/en/function.mysql-insert-id.php

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.