PapaBurgundy Posted May 12, 2011 Share Posted May 12, 2011 I am setting up a PHP & MySql shopping cart. When a user adds products they are stored as sessions. The cart displays the products in an array: foreach($_SESSION as $product => $quantity) So the product is the product_id, and the quantity is the quantity of that product which has been added. When getting the information from the database to display it, it reads like this 1-----2 (product_id = 1, quantity = 2) 2-----1 (product_id = 2, quantity = 1) 3-----3 (product_id = 3, quantity = 3) 11---12 (product_id = 11, quantity = 12) 4-----1 (product_id = 4, quantity = 1) I'm basically trying to insert the product_id and quantity into a table called cart. I've been stuck for days and can still only manage to insert 1 row of values Searching around I saw that some people inserted arrays using implode or explode functions first, but I'm not sure how that would work in this case Any ideas? Quote Link to comment https://forums.phpfreaks.com/topic/236208-inserting-array-of-data-into-database/ Share on other sites More sharing options...
CoalFired - Ben Posted May 12, 2011 Share Posted May 12, 2011 Hi, I'm not sure if this is what you're looking for or not but I have always input data from an array using the following code: <code> $product_id= $_POST['product_id']; $quantity= $_POST['quantity']; for($i = 0; $i < count($product_id); $i++) { if($product_id[$i]) { // <-- QUERY HERE --> } } </code> If you can provide me with some more information on your problem I may be able to help further if this doesn't help you. Regards, Ben Quote Link to comment https://forums.phpfreaks.com/topic/236208-inserting-array-of-data-into-database/#findComment-1214477 Share on other sites More sharing options...
gristoi Posted May 12, 2011 Share Posted May 12, 2011 foreach($_SESSION as $product => $quantity) { INSERT INTO table1 (product_id, quantity) VALUES ('$product', '$quantity') ....... } looks like the session is holding a key-pair array of data, so a simple foreach loop will extract what you need Quote Link to comment https://forums.phpfreaks.com/topic/236208-inserting-array-of-data-into-database/#findComment-1214480 Share on other sites More sharing options...
PapaBurgundy Posted May 12, 2011 Author Share Posted May 12, 2011 Thanks for the help. I did figure it out, and think I deserve a slap in the face for why i couldn't get it to work... The foreach loop worked. But for some reason it just wouldn't insert any of the data into the table until I created an auto incrementing column. That's about 3 days work to figure that out haha Thanks again! Quote Link to comment https://forums.phpfreaks.com/topic/236208-inserting-array-of-data-into-database/#findComment-1214549 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.