Professional CodeIgniter

(singke) #1

Chapter 10: Launch


298


However, before you do all that, you need to make sure that all the data you ’ re sending to the checkout
process are good. For example, are all the products really in the database? Are the prices correct, as far as
you can tell? If the prices have changed since the time the products were put in the Shopping Cart, is
there a warning message? Also, are all prices properly formatted? (As you can see in Figure 10 - 1 , 87.9
should really be 87.90 .)

The first order of business is to add a checkout() function to the Welcome controller. This function will
be the place where you organize all of these features and to which your shoppingcart table will post. For
right now, just create the function bare, as you ’ ll be back to it in a minute:

function checkout(){
//we’ll be right back, folks!
}

Now open the shoppingcart view in an editor, and make sure that the Checkout button posts to
welcome/checkout:

< h1 > Shopping Cart < /h1 >
< div id=’pleft’ >

< ?php echo form_open(‘welcome/checkout’);? >
< table border=’1’ cellspacing=’0’ cellpadding=’5’ >
//snipped

Once you have that in place, it ’ s time to build a verification function in the MOrders model. This
verification function needs to make sure that everything in the model is a valid product and that each
product has a valid price.

The easiest way to do that is to use whatever product IDs are stored in the session cart, extracting
product IDs and prices only from the database, and doing a comparison. If the cart has a product ID that
is not in the database, remove it from the cart. If the price is different in the database, update the
Shopping Cart with the database price. If any changes take place, make a note for the user.

Notice that you ’ ll be making use of the id_clean() function here. It pays to be extra sure that you ’ re
not passing bogus IDs to the database.

function verifyCart(){
$cart = $_SESSION[‘cart’];
$change = false;

if (count($cart)){
foreach ($cart as $id = > $details){
$idlist[] = id_clean($id);
}
$ids = implode(“,”,$idlist);
$this- > db- > select(‘id,price’);
$this- > db- > where(“id in ($ids)”);
$Q = $this- > db- > get(‘products’);
if ($Q- > num_rows() > 0){
Free download pdf