priyabrata sen
priyabrata sen

Reputation: 5

how to select session array and database item to check

i have a session array ie.$_SESSION['cart_array'] and the array contains

Array ( [0] => Array ( [item_id] => qwerty [quantity] => 1 [unit_price] => 500 ) [1] => Array ( [item_id] => skjbm [quantity] => 2 [unit_price] => 100 ) )

now i inserted this array into databse using my sql query..my query is

$insert_query = 'INSERT INTO product_added (id,order_id,email,item_id,unit_price,quantity,total,pay_status) values ';foreach($_SESSION['cart_array'] as $each_item){ 

$insert_query .= "('','$OrderId','','".$each_item['item_id']."','".$each_item['unit_price']."','".$each_item['quantity']."','".$each_item['unit_price']*$each_item['quantity']."',''),";}$query = rtrim($insert_query, ',');if(mysql_query($query)){echo 1;}else{
echo 0;}

my database entry record is

item_id unit_price quantity
qwerty      500       1
skjbm       100       2

till now its ok..... now user update the quatity of existing item_id and the new array is

Array ( [0] => Array ( [item_id] => qwerty [quantity] => 5 [unit_price] => 500 ) [1] => Array ( [item_id] => skjbm [quantity] => 6 [unit_price] => 100 ) )

how can i check the existing entry of data in database with current session and update the specific item_id's quantity if any chagnges happend in cart.thank you in advance

Upvotes: 0

Views: 549

Answers (1)

M.K
M.K

Reputation: 398

Before insert just judge the specific data is existing or not through item id. then the data is not existing in table and do insert , otherwise do update op. Following is my short code for your reference.

<?php

$cart_array = $_SESSION['cart_array'];;
$item_ids = array();
if ($cart_array) {
  foreach ($cart_array as $k => $v) {
    $item_ids[$v['item_id']] = 1;
   }
 }

//before insert do a check
$qry = sprintf("SELECT * FROM product_added WHERE id in (%s)",          implode(',', $item_ids));
$result = mysql_query($qry);
$existing_item_ids = array();
while ($row = mysql_fetch_array($result)) {
     $existing_item_ids[$row['item_id']] = 1;
}
$insrtion_arr = array();
$updated_arr = array();

if (!$existing_item_ids) { // if empty , the all cart data will insert into database
    $insrtion_arr = $item_ids;
  } else {
    foreach ($item_ids as $v) {
           if (isset($existing_item_ids[$v])) {
               $updated_arr[$v] = 1;
           } else {
              $insrtion_arr[$v] = 1;
         }
    }
  }
 //loop cart data and do database operation
 foreach ($cart_array as $k => $v) {
       if (isset($insrtion_arr[$v['item_id']])) {
            // do insert
        }   
       if (isset($updated_arr[$v['item_id']])) {
          // do update                                                                
        }   
    }

Hope this can help you!

Upvotes: 1

Related Questions