如何在PHP上的两个表上插入两个ID

时间:2016-08-29 07:34:29

标签: php mysql

我有2个表tbl_salestbl_customer

enter image description here

当我点击“确认订单”时我希望我的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实现这一目标?

1 个答案:

答案 0 :(得分:1)

首先将新记录插入表tbl_customer并获取最后一个插入ID。使用该id将记录插入表tbl_sales。假设您正在使用pdoauto_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
        ));