简体   繁体   中英

PHP Mysql Foreign Key

I have two mysql tables: 1- customers 2- lite_order

customers table columns: customer_id primary key and Auto Increment field Email hashed_password

lite_order filed contains all the order fields that maybe more than one order belong to same customer and i have many fields. most important ones:

lite_order_id primary key and Auto Increment field customer_id i made it as "index" and from the relation view on phpmyadmin i selected this column as the foreign key to reference to the primary key in the customers table.

The problem is when a new customer signs up, his information goes to the customers table, an d he fills an order form that its data should go to the lite_order table i get an error on this step:

Error: Cannot add or update a child row: a foreign key constraint fails (`DB_NAME`.`lite_order`, CONSTRAINT `lite_order_ibfk_2` FOREIGN KEY (`customer_id`) REFERENCES `customers` (`customer_id`) ON UPDATE CASCADE)

How can i fix this error? i have the customers table working and the customer_id in the customers table have a value now, but i need this value goes also to the customer_id column in the other table once the order form is submitted. and i get this error that!.

By assigning the foreign key "customer_id" into the table "lite_order", you assure a reliability of your data. I mean a lite_order can't be inserted without having a customer.

So you have to insert your customer first, then yours orders.

Depending on what extension you use (mysql, mysqli, pdo), you get the last inserted customer_id by : - mysql - mysqli - pdo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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