且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

同时向父表和子表插入数据

更新时间:2023-02-05 10:08:08

问题在于插入语句的顺序.首先,您尝试向保留表(即子表)中插入一行,但您还没有 cudtomer_id.

The problem is with the order of the insert statements. First, you try to insert a row into the reservations table, which is the child table, but you do not have a cudtomer_id yet.

先将交易放在一边,先插入到客户表中以创建您的客户.根据您的代码,我相信 customer_id 是一个自动增量字段.因此,在插入客户表后调用 mysql_insert_id() 函数检索新创建的客户 ID.

Setting transactions aside, insert first into the customers table to create your customer. Based on your code I belive customer_id is an auto increment field. So, after inserting into the customer table call mysql_insert_id() function to retrieve the newly created customer id.

然后对产品表重复相同的操作.

Then repeat the same with the products table.

最后,执行对预订表的插入,但这次使用您检索到的 2 个 ID 来明确地在查询中提供客户和产品 ID.

Finally, execute the insert into the reservations table, but this time use the 2 ids you retrieved to explicitky provide customer and product ids in the query.

注意1:不要使用mysql扩展,它已被弃用.改用 mysqli 或 PDO.

Note1: do not use mysql extension, it is deprecated. Use mysqli or PDO instead.

注2:可以将上面的inserts封装成一个事务.在生产代码中,我会鼓励你这样做,如果只是为了学习,那么现在不需要打扰.

Note2: you can encapsulate the above inserts into a transaction. In a production code I would encourage you to do so, if it's only for learning, then no need to bother just yet.