php insert multiple rows in MYSQL database

后端 未结 2 776
死守一世寂寞
死守一世寂寞 2021-01-29 08:28

I have a HTML form that i populate from database with a "foreach" loop, so the fields in the name have the same name. The data that i want to post back into the databa

2条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-29 08:53

    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. 
        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();
        }
    }
    

提交回复
热议问题