开发者

PHP beginner: Best practice for inserting into multiple tables with foreign key

开发者 https://www.devze.com 2023-02-09 01:15 出处:网络
I\'m learning basic PHP MySQL right now. As of now I have 2 tables; a zoo table (parent table) and a species table (child table).

I'm learning basic PHP MySQL right now.

As of now I have 2 tables; a zoo table (parent table) and a species table (child table).

The zoo table contains ID (PK) and animal_name. The species table contains an ID (PK) and animal_id (FK; zoo.ID) and species_name.

My question here is what is 开发者_如何学运维the best practice to insert into a multiple table when I create a row in the zoo table.

Currently, the idea that comes to my mind is to have 2 SQL statement and the process is like this:-

  1. Insert animal_name to zoo
  2. Get last ID in zoo table.
  3. Close cursor
  4. Insert animal_id (last insert ID of zoo) and species_name to species table
  5. Close cursor

Is this the best practice? Is there anyway I can improve this process with scalability in mind? (i.e. when I add more tables with foreign key referencing to zoo table in the near future?

I have searched around here and some comrades suggested triggers but however it is not supported in MyISAM storage engine. I'm using MyISAM engine with PHP PDO MySQL object.


With PDO, you can get the ID of the row you just inserted without another query - just do
$newRowID = $conn->lastInsertId();

where $conn is your database connection.


Use the MySQL built-in facilities for finding the last generated identity.

So for your Item 2, use this SQL statement:

`SELECT LAST_INSERT_ID()`

This gets the last auto incremented ID on your connection. Load that value into a variable, and use that in your Item 4 INSERT statement.

How to Get the Unique ID for the Last Inserted Row with MySQL

0

精彩评论

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