Jump to content

For loop in Session Array in Update SQL Statement


billy_111

Recommended Posts

Hey,

 

I am trying to update a table based on values from a session array in a shopping basket.

 

When i add to cart i have the following method:

 

    public function AddToCart(){
        !isset($_SESSION['ID']) ? $_SESSION['ID'] = array() : '';
        !isset($_SESSION['theName']) ? $_SESSION['theName'] = array() : '';
        !isset($_SESSION['quantity']) ? $_SESSION['quantity'] = array() : '';
        !isset($_SESSION['price']) ? $_SESSION['price'] = array() : '';
        !isset($_SESSION['image']) ? $_SESSION['image'] = array() : '';

        array_push($_SESSION['ID'], $_POST['ID']);
        array_push($_SESSION['theName'], $_POST['theName']);
        array_push($_SESSION['quantity'], $_POST['quantity']);
        array_push($_SESSION['price'], $_POST['price']);
        array_push($_SESSION['image'], $_POST['image']);
        $loc = $_SERVER['HTTP_REFERER'];
        echo "<script>window.location.href='".$loc."'</script>";
    }

 

Now when someone confirms an order i need to update the stock list to mange the stock control. Therefore i need to update the stock value based on the quantities of the items in the basket.

 

So i tried doing this:

 

    public function deductQuantitiesFromItems(){
        $i=0;
        session_start();
        foreach($_SESSION['ID'] as $ID):
        $sql = 'UPDATE hussaini_items SET
                    stock = stock - '.$_SESSION['quantity'][$i].' 
                    WHERE ID = '.$ID;
            $result = $this->mysqli->query($sql) or die($this->mysqli->query($sql));
            return $result;
        $i++;
        endforeach;
    }

 

I get this error:

 

Warning: Invalid argument supplied for foreach() in G:\xampp\htdocs\Manstore\Models\Cart.class.php  on line 121

 

Why doesn't the update work?

 

Thanks again

When you do this:

<?php
!isset($_SESSION['ID']) ? $_SESSION['ID'] = array() : '';
?>

and $_SESSION['ID'] is already set, you're making it the null string (which is not an array). This is where a plain "if" would be better:

<?php
if (!isset($_SESSION['ID'])) {
   $_SESSION['ID'] = array();
}
?>

 

Ken

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.