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:-
- Insert animal_name to zoo
- Get last ID in zoo table.
- Close cursor
- Insert animal_id (last insert ID of zoo) and species_name to species table
- 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
精彩评论