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.

Link to comment
Share on other sites

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");

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.