我有2个表tbl_sales
和tbl_customer
当我点击“确认订单”时我希望我的tbl_sales
包含此值
sale_id customer_id product_name product_qty product_price
1 1 Coca-Cola2 25 13
2 1 Pepsi 25 12
3 1 Nescafe 25 12
我的tbl_customer
包含此值
customer_id customer_firstname customer_address customer_contact
1 John #3 St. Boulevard 123456789123
如何使用PHP和MySQL实现这一目标?
答案 0 :(得分:1)
首先将新记录插入表tbl_customer
并获取最后一个插入ID。使用该id将记录插入表tbl_sales
。假设您正在使用pdo
和auto_increment
这样的内容:
//create a prepared statement for inserting into the customer table
$prepStmt= $pdo->prepare("INSERT INTO tbl_customer (customer_firstname, customer_address, customer_contact)
VALUES(:firstname, :address, :contact)");
$prepStmt->execute(array(
"firstname" => $_POST['yourFormValueForFirstname'], //TODO: add validation for $_POST variables because of XSS-attacks!
"address" => $_POST['yourFormValueForAddress'],
"contact" => $_POST['yourFormValueForContact']
));
//now get the last inserted id
$lastCustomerId = $pdo->lastInsertId();
//create a prepared statement for inserting into sales table
$prepStmt= $pdo->prepare("INSERT INTO tbl_sales (customer_id,product_name, product_qty, product_price)
VALUES(:customerId, :prodName, :prodQ,:prodPrice)");
//and use the last inserted customer id for the new sales record
$prepStmt->execute(array(
"customerId" => lastCustomerId,
"prodName" => $productName,
"prodQ" => $productQuantity,
"prodPrice" => $productPrice
));