aidaghazaryan aidaghazaryan - 6 months ago 21
MySQL Question

How to insert shopping cart orders of each user into one column in DB (not row)?

I have shopping cart in my wordpress website and once user clicked "Place order" button, I want to insert corresponding user's cart items into DB, but want to insert it in one column. Let me make it more clearer.

I'm tracking user's name/surname/mail/phone number and have columns for each of those info in DB. Also I have a column named "cartInfo" and there I want to insert ALL cart items separated with commas or something else (it doesn't matter). I want to collect all cart items info together and insert it in that one column. Currently I'm inserting them as multiple rows (one cart item = one row in DB). Here is my code for that.

foreach($_SESSION['shopping_cart'] as $item) {
$item_id = $item['product_id'];
$item_name = $item['product_name'];
$item_quantity = $item['product_quantity'];
$item_url = $item['product_url'];
$item_code = $item['product_code'];

$sql = "INSERT INTO cart_orders (productcode, productqty) VALUES ('$item_code', '$item_quantity')";
if(mysql_query($sql)){
echo 'Success';
}else{
echo mysql_error();
}
}


But I want to collect all info together.

Answer

You can insert all row in single column below. Check comment after line

 foreach ($_SESSION['shopping_cart'] as $item) {

            $product_quantity .=$item['product_quantity'] . ",";//concatenate it by comma
            $item_code .=$item['product_code'] . ",";//concatenate it by comma
        }// foreach loop end
        $product_quantity = rtrim($product_quantity, ",");// Remove last comma
        $item_code = rtrim($item_code, ",");// remove last comma
        $sql = "INSERT INTO cart_orders (productcode, productqty) VALUES ('$item_code', '$product_quantity')";
        if (mysql_query($sql)) {
            echo 'Success';
        } else {
            echo mysql_error();
        }

Updated

foreach ($_SESSION['shopping_cart'] as $item) {
            $product_quantity .=$item['product_quantity'] ."-". $item['product_code'] . ",";  //concatenate it by comma
        }// foreach loop end
        $product_quantity = rtrim($product_quantity, ","); // Remove last comma

        $sql = "INSERT INTO cart_orders (productcode) VALUES ('$product_quantity')";
        if (mysql_query($sql)) {
            echo 'Success';
        } else {
            echo mysql_error();
        }
Comments