简体   繁体   English

PHP初学者:使用外键插入多个表的最佳实践

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

I'm learning basic PHP MySQL right now. 我现在正在学习基本的PHP MySQL。

As of now I have 2 tables; 截至目前,我有2张桌子; a zoo table (parent table) and a species table (child table). zoo表(父表)和species表(子表)。

The zoo table contains ID (PK) and animal_name . zoo表包含ID (PK)animal_name The species table contains an ID (PK) and animal_id (FK; zoo.ID) and species_name . species表包含一个ID (PK)animal_id (FK; zoo.ID)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. 我的问题是在zoo表中创建一行时插入多表的最佳实践是什么。

Currently, the idea that comes to my mind is to have 2 SQL statement and the process is like this:- 目前,我想到的想法是拥有2条SQL语句,过程如下:

  1. Insert animal_name to zoo 在动物园中插入animal_name
  2. Get last ID in zoo table. 获取动物园表中的最后一个ID。
  3. Close cursor 关闭光标
  4. Insert animal_id (last insert ID of zoo) and species_name to species table 在物种表中插入animal_id(动物园的最后插入ID)和species_name
  5. Close cursor 关闭光标

Is this the best practice? 这是最佳做法吗? Is there anyway I can improve this process with scalability in mind? 无论如何,我是否可以考虑可伸缩性来改进此过程? (ie when I add more tables with foreign key referencing to zoo table in the near future? (即当我在不久的将来添加更多带有外键的表引用zoo表时?

I have searched around here and some comrades suggested triggers but however it is not supported in MyISAM storage engine. 我在这里搜索了一些同志建议的触发器,但是MyISAM存储引擎不支持它。 I'm using MyISAM engine with PHP PDO MySQL object. 我正在将MyISAM引擎与PHP PDO MySQL对象一起使用。

With PDO, you can get the ID of the row you just inserted without another query - just do 使用PDO,无需其他查询即可获取刚刚插入的行的ID-只需执行
$newRowID = $conn->lastInsertId();

where $conn is your database connection. $ conn是您的数据库连接。

Use the MySQL built-in facilities for finding the last generated identity. 使用MySQL内置工具查找最后生成的身份。

So for your Item 2, use this SQL statement: 因此,对于您的项目2,请使用以下SQL语句:

`SELECT LAST_INSERT_ID()`

This gets the last auto incremented ID on your connection. 这将获取您连接上的最后一个自动递增的ID。 Load that value into a variable, and use that in your Item 4 INSERT statement. 将该值加载到变量中,然后在您的Item 4 INSERT语句中使用它。

How to Get the Unique ID for the Last Inserted Row with MySQL 如何使用MySQL获取最后插入行的唯一ID

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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