Jump to content

[SOLVED] Structure for multiple row insert from sessions using php


phpdragon

Recommended Posts

MySQL version 5.0.75

 

I have a cart that stores items in sessions, I would like to know how to structure the sql query so it does a multiple row insert of all the products in the session cart.

 

I have attempted it with the following code but I only get the first item in the cart entered into the database and it shows me the error of the next entry to go into the database.

 

$orderTable=$userID."_orders";
for ($i=0; $i<$ses_basket_items; $i++){
  $price=sprintf("%01.2f",$ses_basket_price[$i]);
  $quantity=$ses_basket_amount[$i];
  $code=$ses_basket_stockcode[$i];
  $itemID=$ses_basket_id[$i];
  $product=$ses_basket_name[$i];
  $unit=sprintf("%01.2f",($price/$quantity));
// add item to users order table
$sql="INSERT INTO $orderTable VALUES ('".mysql_real_escape_string($thisID)."', '".mysql_real_escape_string($product)."', '".mysql_real_escape_string($itemID)."', '".mysql_real_escape_string($quantity)."', '".mysql_real_escape_string($code)."', '".mysql_real_escape_string($unit)."')";
$result=mysql_query($sql) or die ("Error in query: $sql");
}

 

I have echoed $session_basket_items and it tells my the right number of entries that need to go in, I am assuming it is because it needs a (,) after each insert that it fails, but I dont know how to do this.

Thabkyou for taking the time to answer fenway, the problem is now solved here is the query I was looking for.

 

$sql="INSERT INTO $orderTable VALUES";
for ($i=0; $i<$ses_basket_items; $i++){
  $price=sprintf("%01.2f",$ses_basket_price[$i]);
  $quantity=$ses_basket_amount[$i];
  $code=$ses_basket_stockcode[$i];
  $itemID=$ses_basket_id[$i];
  $product=$ses_basket_name[$i];
  $unit=sprintf("%01.2f",($price/$quantity));
  $allocated='0';
  $sql .= " ('$thisID', '$product', '$itemID', '$quantity', '$code', '$unit', '$allocated'),";
}
$sql = substr($sql,0,-1); //this removes last comma
$result=mysql_query($sql) or die (mysql_error().": $sql");

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.