开发者

how to connect two mysql tables in which I am inserting data in same time

How to connect two mysql tables in which I am inserting data in same time?

I have table customers which is my app table, and I have user which is used by library I use for my framework, this library handles users and authorization.

I wanted to have user_id (which is id from user) in customers, but I am creating those two tables in same开发者_开发知识库 time.

Any ideas? Thanks!


the php command mysql_insert_id gives you the id of the last record inserted into a table. So from my undestanding if your inserting a user you could get the id then insert that into another table?

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

Or have I understood your question wrongly?


It is simply not possible. Nothing can happen at the same time in a program.

What is possible is to:

  • Start a database transaction
  • perform your first query
  • retrieve the table's key; if it's an autoincrement, there are built-in ways to retrieve the last inserted key in every database API
  • perform your second query using the retrieved key as a parameter
  • Commit the transaction; But if an error occurred, you need to rollback the whole transaction

This is how it is done, and it behaves exactly like you want it to.


How about a link table?

users_customers
user_id | customer_id
=====================
 1      |  648785552
 5      |  145778304
 4      |  654566055

You can then join the tables together using this table, for example like this:

SELECT users.name, customers.address
  FROM users
  JOIN users_customers
    ON users_customers.user_id = users.id
  JOIN customers
    ON users_customers.customer_id = customers.id
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜