且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

php在MYSQL数据库中插入多行

更新时间:2023-12-04 12:58:04

如果要从HTML表单中获取数组,则需要循环访问此数组并将每一行分别插入DB.为此,您需要使用准备好的语句和循环.

If you are getting an array from your HTML form then you need to loop on this array and insert each row separately into DB. To do this you need to use prepared statement and a loop.

if (isset($_GET['submit'])) {
    $client_id = $value->ID; // Wherever this value comes from...

    // Insert new sales order
    $stmt = $mysql->prepare('INSERT INTO salesorder (client_id) VALUES (?)');
    $stmt->bind_param('s', $client_id);
    $stmt->execute();
    $stmt->store_result();

    $order_id = $mysql->insert_id;

    // prepare the SQL statement
    $orderline_stmt = $mysql->prepare('INSERT INTO orderline (order_id, food_id, qty) VALUES (?,?,?)');

    // loop on each element from HTML form 
    // i.e. <input name="foodid[]" >
    foreach ($_GET['foodid'] as $key => $food_id) {
        $qty = $_GET['qty']; // should this be an array too?
        // $qty = $_GET['qty'][$key]; <-- if it's also an array

        $orderline_stmt->bind_param('sss', $order_id, $food_id, $qty);
        $orderline_stmt->execute();
    }
}