Professional CodeIgniter

(singke) #1

Chapter 10: Launch


299


foreach ($Q- > result_array() as $row){
$db[$row[‘id’]] = $row[‘price’];
}
}
foreach ($cart as $id = > $details){
if (isset($db[$id])){
if ($details[‘price’] != $db[$id]){
$details[‘price’] = $db[$id];
$change = true;
}
$final[$id] = $details;
}else{
$change = true;
}
}

$totalprice=0;
foreach ($final as $id = > $product){
$totalprice += $product[‘price’] * $product[‘count’];
}

$_SESSION[‘totalprice’] = $totalprice;
$_SESSION[‘cart’] = $final;
$this- > session- > set_flashdata(‘change’,$change);
}else{
//nothing in cart!
$this- > session- > set_flashdata(‘error’,”Nothing in cart! Please notify
[email protected] to report this problem during checkout.”);
}
}

In the above code, when you extract the products from the database and then loop through the cart, it ’ s
an opportunity to check to make sure that the product is valid and that the price is still good. If a price
changes, then set the $change variable to TRUE. The same thing goes if you find that one or more
products aren ’ t in the database.

Notice the else branch in the verifyCart() function? It serves a very important purpose, but the
message it delivers to the end - user will hardly ever be seen because it only shows up if the Shopping
Cart is empty. At the point at which the user checks out, he or she is doing so from a page that has
already been loaded from the Shopping Cart, so it is highly unlikely that the Shopping Cart will
disappear between then and the verification process.

However, you might have a situation involving some kind of PHP session time - out or a malicious user
trying to access the checkout page without first putting any items in the cart. If that ’ s the case, you
really want this little check in there. Feel free to customize the message any way you like.

At the end of the process, you are left with a brand - new array called $final , and that ’ s what you write
back to the PHP session.

Free download pdf