An7hony Posted February 9, 2012 Share Posted February 9, 2012 Hi i am trying to pass values from a cart to a database using foreach. This is my code: $columns = array('order_id', 'order_item_id', 'order_product_name', 'order_product_dimensions', 'order_product_options', 'order_product_quantity', 'order_product_price', 'order_product_subtotal', 'order_product_vat', 'order_product_delivery','order_product_total','order_product_sku','order_product_image_name','order_product_image_type','order_product_image_path','order_product_image_size','order_product_artwork_link','order_product_artwork_name','order_product_artwork_type','order_product_artwork_path','order_product_artwork_size','order_firstname','order_lastname','order_companyname','order_email','order_tel','order_billing_address','order_billing_address2','order_billing_town','order_billing_county','order_billing_postcode','order_shipping_address','order_shipping_address2','order_shipping_town','order_shipping_county','order_shipping_postcode','order_status','order_username'); $data = array_fill_keys($columns, 'NULL'); foreach($data as $key => $value) { $data[$key] = empty($_POST[$key]) ? 'NULL' : "'".mysql_escape_string($_POST[$key])."'"; $query = "INSERT INTO orders (id, order_created_at, ".implode(", ",$columns).") VALUES (null, NOW(), ".implode(",",$data).')'; } Problem is posting 2 or more products into the database. How do i split the values so it enters each product into the database? Quote Link to comment https://forums.phpfreaks.com/topic/256737-foreach/ Share on other sites More sharing options...
scootstah Posted February 9, 2012 Share Posted February 9, 2012 You would need to separate each set of values with a comma, and then you will insert multiple rows. Also, take the actual INSERT query out of the loop since you only want that to happen once. Your query should look like INSERT INTO orders (column1, column2, column2) VALUES (1,2,3), (4,5,6), (7,8,9) Quote Link to comment https://forums.phpfreaks.com/topic/256737-foreach/#findComment-1316116 Share on other sites More sharing options...
An7hony Posted February 9, 2012 Author Share Posted February 9, 2012 thanks you set me on the right path, i added a ++$count; to do the bit you suggested Quote Link to comment https://forums.phpfreaks.com/topic/256737-foreach/#findComment-1316152 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.