SQL查询将多个数组值插入数据库

时间:2018-09-23 19:40:25

标签: php sql arrays

我从购物车表中获取数组值,我想将购物车数组值插入我的订单表中,但是我面临的问题是仅将最后一个数组值插入数据库中,但我想将所有购物车值插入到我的数据库中订单表。

/*This is the form page I was getting cart value*/
<form>
<input type="text" name="cid[]" value="1">
<input type="text" name="pid[]" value="2">
<input type="text" name="quantity[]" value="3">
<input type="text" name="total[]" value="5">
</form>

/*Once the form is submited the action comes to this php page*/

<?php 
$cid = $_POST['cid'];
$pid = $_POST['pid'];
$quantity = $_POST['quantity'];
$total = $_POST['cid'];

$insertquery = "INSERT INTO orders(cid,pid,quantity,total) VALUES('$cid','$pid','$quantity','$total')";

?>


/*After excution of this code only inseting the last value, not inserting the all value */

1 个答案:

答案 0 :(得分:0)

由于表单元素是数组[],因此可以像这样遍历它们:

$rowCount = count($_POST['cid']);

for($=0; $i < $rowCount; $i++) {

    $cid = $_POST['cid'][$i];
    $pid = $_POST['pid'][$i];
    $quantity = $_POST['quantity'][$i];
    $total = $_POST['total'][$i];

    // ...

}