jeudi 23 juin 2016

Loop through result set before inserting data into DB

I currently have a products page and a shopping cart. When users add items to the cart i am inserting the products into the db once the user checkout. But at the present moment only the first product is inserted into the cart.

I was wondering if there is a way to loop through the data before it is inserted in the db, to ensure all the products are inserted into the db and not just the 1st. But i have no idea how to do this, I would usually do this using foreach, but i cannot do this in this case as the information i need to loop such as the products name and price is selected from a db, therefore there is no array.

So my question is, how would i loop through all results before inserting, and what is the best practise to do so. Any help would be greatly appreciated.

    $vi_details = mysqli_query($dbc, "SELECT Resturant_name,City_name FROM Rest_Details WHERE Resturant_ID='$_SESSION[rest_id]'");

    while ($row_details = mysqli_fetch_array($vi_details)) {
        $rest_name = $row_details['Resturant_name'];
        $City_name = $row_details['City_name'];


        $_query = "INSERT INTO ord_dets(Order_ID,custmer_ip,Resturant_ID,Resturant_name,City_name,
        Product_Id,Product_Name,Product_Price,item_sub) 
VALUES (?,?,?,?,?,?,?,?,?)";
        $query_run = $dbc->prepare($_query);


        $query_run->bind_param('isissisdd', $OI, $ip, $_SESSION['rest_id'], $rest_name, $City_name, $Product_Id, $product_name, $prod_price,$item_sub);

        if (!$query_run->execute()) {
            $insertError = "There was an error inserting data: " . $query_run->error;
        }

        print "affected rows:" . $query_run->affected_rows; //how many records affected?    
    }
}

The code for this page is pretty long, all the variables above has been defined through out the page, the data inserts fine.

Aucun commentaire:

Enregistrer un commentaire