插入数组值使用php和PDO将单个ID插入到MySQL数据库中

问题描述:

使用带有Ajax加载的数组插入将多个乘积插入单个id.也许使用Explode,但是需要针对此类输出的明确说明:

Insert multi product into single id using array insertions with Ajax load. Maybe use Explode but need a clear instruction for this type of output:

所有产品(问题)都将输入到一个ID中.这些问题列表由Ajax添加.

all product (problem) will input into one single id. Those problem list are added by Ajax.

<?php
if(isset($_POST['Submit'])){
    try {
    $serviceTitle = $_POST['serviceTitle'];
    $price = $_POST['price'];
    $quantity = $_POST['quantity'];
    $amount = $_POST['amount'];

    $date = date('Y-m-d');
    date_default_timezone_set('Asia/Dacca'); 
    $time = date('h:i:s');
    $createBy = $_SESSION['sess_username'];

    $_SESSION['orderNo'] = $_POST['orderNo'];
    $_SESSION['customerNo'] = $_POST['customerNo'];

    if($_POST['Submit']==='Submit'){
        for($i=0;$i<count($serviceTitle);$i++){
            $statement = $db->prepare("INSERT INTO invoice (orderNo,customerNo,productName,price,quantity,amount,createDate,createTime,createBy) VALUES (?,?,?,?,?,?,?,?,?)");
            $statement->execute(array($_POST['orderNo'],$_POST['customerNo'],$serviceTitle[$i],$price[$i],$quantity[$i],$amount[$i],$date,$time,$createBy));
        }
    }
    header("location: order_confirm_tech_step2.php");
    }
    catch(Exception $e) {
            $error_message = $e->getMessage();
    }
}
?>

它将以相同的orderNo和customerNo插入,但是我想这样插入数据行: 预先感谢.

It will insert at same orderNo and customerNo but I want to insert data row like this: thanks in advance.

您好,我认为最好的方法是为所有插入器指定不同的名称,例如'new_screen_price' 'old_screen_price'

Hi the best way I think is to give different name for all inpunt like 'new_screen_price' 'old_screen_price'

如果您的表单是由js生成的,那么如果您没有将其直接放在html中,则可以执行此操作

if your form is generate by js you can do this if isn't put direct in html you have

<input name='new_screen_price'>
<input name='new_screen_qty'>
...

在php中选择单个值后

after you take your single value in php like

$newScreen = [];
$newScreen['name'] = 'new screen';
$newScreen['price'] = $_POST['new_screen_price'];

将您的阵列产品合而为一

put yours array product in one

$products = [];
$products['newScreen'] = $newScreen;

您准备好了,我只需要两个参数的价格和名称,但是显然您需要所有

you are ready for you request i just do for two params price and name but oviously you need for all

foreach($products as $prod){
   $statement = $db->prepare("INSERT INTO invoice (orderNo,customerNo,productName,price,quantity,amount,createDate,createTime,createBy) VALUES (?,?,:name,:price,...)");
   $statement->bindParam(':name', $prod->name);
   $statement->bindParam(':price', $prod->price);
   $statement->execute();
}

美好的一天,我希望这可以为您提供帮助

good day i hope this can help you