如何使用for循环插入数据库

时间:2019-05-21 02:22:15

标签: php mysql

我正在尝试使用for循环将数据插入数据库中,并且似乎代码中没有错误,因为编译器不会提示任何错误,但是当我单击“提交”按钮时,未插入数据

我只尝试了mysqli,因为它是我最熟悉的

$db = mysqli_connect('localhost','root','','generator');

$statement = mysqli_query($db, 'SELECT LAST_INSERT_ID()');

$order_id = mysqli_fetch_array($statement);

for($count=0; $count<$_POST["total_item"]; $count++)
{

    $statement = $db->prepare("
        INSERT INTO docgenitem
        (order_id, vendor, itemdescription, order_item_quantity, order_item_price, order_item_actual_amount )
        VALUES (:order_id, :vendor, itemdescription, :order_item_quantity, :order_item_price, :order_item_actual_amount)
    ");

    $statement->execute(
        array(
        ':order_id'               =>  $order_id,
        ':vendor'                 =>  trim($_POST["item_name"][$count]),
        ':itemdescription'          =>  trim($_POST["itemdescription"][$count]),
        ':quantity'          =>  trim($_POST["order_item_quantity"][$count]),
        ':priceperunit'          =>  trim($_POST["order_item_price"][$count]),
        ':amount'           =>  trim($_POST["order_item_final_amount"][$count]),
        )
    );
}

1 个答案:

答案 0 :(得分:0)

您的代码应为:

$db = new mysqli('localhost','root','','generator');

$order_id = $db->insert_id;

for($count=0; $count<$_POST["total_item"]; $count++)
{

    $s1 = trim($_POST["item_name"][$count]);
    $s2 = trim($_POST["itemdescription"][$count]);
    $s3 = trim($_POST["order_item_quantity"][$count]);
    $s4 = trim($_POST["order_item_price"][$count]);
    $s5 = trim($_POST["order_item_final_amount"][$count]);

    $statement = $db->prepare("
        INSERT INTO docgenitem
        (order_id, vendor, itemdescription, order_item_quantity, order_item_price, order_item_actual_amount )
        VALUES (?, ?, ?, ?, ?, ?)
    ");

    $statement->bind_param('dsssss', $order_id, $s1, $s2, $s3, $s4, $s5);
    $statement->execute();
}

$statement->close();

$db->close();