Jump to content

Inserting array of data into database


PapaBurgundy

Recommended Posts

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?

Link to comment
https://forums.phpfreaks.com/topic/236208-inserting-array-of-data-into-database/
Share on other sites

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

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!

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.