如何将数据插入两个不同的表? [英] How do insert data into two different tables?
问题描述
我有一张表格,其中包含用户详细信息和他们上传的图像.我想将数据写入用户表和图像表,但是我非常确定,仅凭两个单独的插入语句就无法完成数据.任何帮助将不胜感激.
I have a form which takes both the user details and an image uploaded by them. I want to write the data to a user table and an image table but i am pretty sure that it cannot be done with just two separate insert statements. Any help would be much appreciated.
推荐答案
您需要先插入用户,然后执行"SELECT LAST_INSERT_ID()"以检索用户的ID.然后,您可以使用新创建的用户ID将图像插入图像表中.在PHP中,您实际上可以使用 mysql_insert_id()来检索新ID.如果您将mysql与InnoDB一起使用,则还可以将插入内容包装在
You need to insert the user first, then do "SELECT LAST_INSERT_ID()" to retrieve the id of the user. Then you can insert the image in the image table with the newly created user id. In PHP you can actually use mysql_insert_id() to retrieve the new id. If you use mysql with InnoDB, you can also wrap the inserts in a transaction, by issuing BEGIN, followed by the INSERTs, followed by either COMMIT if everything is successfully added, or ROLLBACK in case of failure.
这篇关于如何将数据插入两个不同的表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!