如何使用相应的字段将值从一个表插入另一个表

时间:2016-08-30 02:29:38

标签: php mysql

我有两个表,tbl_carttbl_sales

我的购物车有两个字段product_idquantityCart

//SELECT ALL FROM CART
$insertCustomer = "SELECT * FROM cart;";
$exec = mysqli_query($connection, $insertCustomer);

//ASSIGN EACH ROW TO $cart_array
$cart_array = array();
while ($row = mysqli_fetch_array($exec)) {
    $cart_array[] = array(
        "product_id" => $row['product_id'], 
        "quantityCart" => $row['quantityCart'], 
    );
}

print_r($cart_array)告诉我这些:

Array ( [0] => Array ( [product_id] => 1 [quantityCart] => 20 ) 
        [1] => Array ( [product_id] => 2 [quantityCart] => 20 ) 
        [2] => Array ( [product_id] => 3 [quantityCart] => 20 ) 
        [3] => Array ( [product_id] => 4 [quantityCart] => 20 ) )

我的tbl_sales包含以下字段sale_id(主要和AI),product_idproduct_quantity

我想实现类似的东西,但是使用数组:

INSERT INTO sales (product_id, product_quantity) VALUES (1,20) INSERT INTO sales (product_id, product_quantity) VALUES (1,20) INSERT INTO sales (product_id, product_quantity) VALUES (1,20) INSERT INTO sales (product_id, product_quantity) VALUES (1,20)

现在我的问题是如何使用PHP / SQL实现这一目标?

1 个答案:

答案 0 :(得分:2)

如何在一个查询中完成所有这些操作?如果我理解代码的意图:

INSERT INTO sales(product_id, product_quantity) 
    SELECT product_id, quantityCart
    FROM cart;