SitePoint Sponsor

User Tag List

Results 1 to 13 of 13
  1. #1
    SitePoint Evangelist
    Join Date
    Apr 2007
    Posts
    398
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Getting the value from POST and putting it into a switch statement

    Hi All,

    I'm still having some problems with a shopping cart script which Ernie1 kindly helped me with last time I had a problem. It's driving me bonkers! Basically I have a simple dropdown menu on my page on a simple shopping cart script:

    PHP Code:
    <select name="qty" id="qty">
     <
    option selected="selected" value="1">1</option>
     <
    option value="2">2</option>
     <
    option value="3">3</option>
     <
    option value="4">4</option>
     <
    option value="5">5</option>
     </
    select>
    <
    input type="submit" value="Add to Cart" name="submit" /> 
    and when I hit submit I print this value to the next page:

    PHP Code:
    print_r($_POST); 
    Code:
    Array ( [qty] => 4 [submit] => Add to Cart )
    As you will see by testing my page here:

    http://www.inspireaway.co.uk/cart/

    But nomatter how many qty I select from the first page only ONE item is always added to the cart.

    I know I have to somehow take qty from $_POST and somehow put it in my case statement for 'add' at this part, but i'm not sure how. Here's my code can anyone kindly help?

    cart.php

    PHP Code:
    <?php
    // Start the session
    session_start();
    // Process actions

     
    print_r($_POST); 


    $cart $_SESSION['cart'];
    $action $_GET['action'];
    switch (
    $action) {
        case 
    'add':
            if (
    $cart) {
                
    $cart .= ','.$_GET['id'];
            } else {
                
    $cart $_GET['id'];
            }
            break;
        case 
    'delete':
            if (
    $cart) {
                
    $items explode(',',$cart);
                
    $newcart '';
                foreach (
    $items as $item) {
                    if (
    $_GET['id'] != $item) {
                        if (
    $newcart != '') {
                            
    $newcart .= ','.$item;
                        } else {
                            
    $newcart $item;
                        }
                    }
                }
                
    $cart $newcart;
            }
            break;
        case 
    'update':
        if (
    $cart) {
            
    $newcart '';
            foreach (
    $_POST as $key=>$value) {
                if (
    stristr($key,'qty')) {
                    
    $id str_replace('qty','',$key);
                    
    $items = ($newcart != '') ? explode(',',$newcart) : explode(',',$cart);
                    
    $newcart '';
                    foreach (
    $items as $item) {
                        if (
    $id != $item) {
                            if (
    $newcart != '') {
                                
    $newcart .= ','.$item;
                            } else {
                                
    $newcart $item;
                            }
                        }
                    }
                    for (
    $i=1;$i<=$value;$i++) {
                        if (
    $newcart != '') {
                            
    $newcart .= ','.$id;
                        } else {
                            
    $newcart $id;
                        }
                    }
                }
            }
        }
        
    $cart $newcart;
        break;
    }
    $_SESSION['cart'] = $cart;
    ?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
        
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
        <title>PHP Shopping Cart Demo  Cart</title>
        <link rel="stylesheet" href="css/styles.css" />
    </head>

    <body>

    <div id="shoppingcart">

    <h1>Your Shopping Cart</h1>

    <?php

    function writeShoppingCart() {
        
    $cart $_SESSION['cart'];
        if (!
    $cart) {
            return 
    '<p>You have no items in your shopping cart</p>';
        } else {
            
    // Parse the cart session variable
            
    $items explode(',',$cart);
            
    $s = (count($items) > 1) ? 's':'';
            return 
    '<p>You have <a href="cart.php">'.count($items).' item'.$s.' in your shopping cart</a></p>';
        }
    }

    echo 
    writeShoppingCart();
    ?>

    </div>

    <div id="contents">

    <h1>Please check quantities...</h1>

    <?php

    function showCart() {
        global 
    $db;
        
    $cart $_SESSION['cart'];
        if (
    $cart) {
            
    $items explode(',',$cart);
            
    $contents = array();
            foreach (
    $items as $item) {
                
    $contents[$item] = (isset($contents[$item])) ? $contents[$item] + 1;
            }
            
    $output[] = '<form action="cart.php?action=update" method="post" id="cart">';
            
    $output[] = '<table>';
            foreach (
    $contents as $id=>$qty) {
                
    $sql 'SELECT * FROM books WHERE id = '.$id;
                
    $result $db->query($sql);
                
    $row $result->fetch();
                
    extract($row);
                
    $output[] = '<tr>';
                
    $output[] = '<td><a href="cart.php?action=delete&id='.$id.'" class="r">Remove</a></td>';
                
    $output[] = '<td>'.$title.' by '.$author.'</td>';
                
    $output[] = '<td>&pound;'.$price.'</td>';
                
    $output[] = '<td><input type="text" name="qty'.$id.'" value="'.$qty.'" size="3" maxlength="3" /></td>';
                
    $output[] = '<td>&pound;'.($price $qty).'</td>';
                
    $total += $price $qty;
                
    $output[] = '</tr>';
            }
            
    $output[] = '</table>';
            
    $output[] = '<p>Grand total: <strong>&pound;'.$total.'</strong></p>';
            
    $output[] = '<div><button type="submit">Update cart</button></div>';
            
    $output[] = '</form>';
        } else {
            
    $output[] = '<p>You shopping cart is empty.</p>';
        }
        return 
    join('',$output);
    }


    echo 
    showCart();
    ?>

    <p><a href="index.php">Back to bookshop...</a></p>

    </div>

    </body>
    </html>

  2. #2
    Theoretical Physics Student bronze trophy Jake Arkinstall's Avatar
    Join Date
    May 2006
    Location
    Lancaster University, UK
    Posts
    7,062
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    To be honest, the way you have that cart set up isn't as efficient as it could/should be, especially when it comes to adding quantities.

    Currently you have your cart set up so that:
    PHP Code:
    $_SESSION['cart'] = '{id},{id},{id},{id},{id},{id}'
    A preferable system would be:
    PHP Code:
    $_SESSION['cart'][{id}] = {qty}; 
    I.e. if you had product #26 and wanted 3 of them:
    PHP Code:
    $_SESSION['cart'][26] = 3
    voila.


    By the way, you'll find things more readable if you create functions to do tasks such as adding an item, removing an item etc. They may only be used once, but it will still be easier.
    Jake Arkinstall
    "Sometimes you don't need to reinvent the wheel;
    Sometimes its enough to make that wheel more rounded"-Molona

  3. #3
    Theoretical Physics Student bronze trophy Jake Arkinstall's Avatar
    Join Date
    May 2006
    Location
    Lancaster University, UK
    Posts
    7,062
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Okay, I thought I'd help out a bit; I felt the urge to write some PHP and I needed a break from biology revision!!!

    So, create a file called cart.class.php and put the following into it:
    PHP Code:
    <?php
    class Cart{
        protected 
    $Cart = array();
        static function 
    ConstructFromSession($CartSessionKey 'cart'){
            if(!
    Array_Key_Exists($CartSessionKey$_SESSION)) $_SESSION[$CartSessionKey] = array();
            return new 
    Cart($_SESSION[$CartSessionKey]);
        }
        function 
    __Construct(array &$Cart){
            
    $this->Cart =& $Cart;
        }
        function 
    Add($ProductID$Qty 1){
            
    $Product =& $this->Get($ProductID);
            
    $Product += (int)$Qty;
            
    $this->Filter();
        }
        function 
    SetQty($ProductID$Qty 1){
            
    $Product =& $this->Get($ProductID);
            
    $Product $Qty;
            
    $this->Filter();
        }
        function 
    Remove($ProductID$Qty null){
            if(
    is_null($Qty)){
                
    $Qty $this->Get($ProductID);
            }
            
    $this->Add($ProductID, -$Qty);
        }
        function 
    Exists($ProductID){
            
    $this->Filter();
            return 
    Array_Key_Exists($ProductID$this->Cart);
        }
        function &
    Get($ProductID){
            if(!
    $this->Exists($ProductID)){ $this->Cart[$ProductID] = 0; }
            return 
    $this->Cart[$ProductID];
        }
        function 
    Filter(){
            foreach(
    $this->Cart as $ProductID => &$Qty){
                if(
    $Qty <= 0) unset($this->Cart[$ProductID]);
            }
        }
        function 
    NumberOfItems(){
            
    $this->Filter();
            return 
    Count($this->Cart);
        }
        function 
    Render($Database){
            if(
    $this->NumberOfItems() == 0){
                return 
    '<p>You shopping cart is empty.</p>';
            }else{
                
    $total 0;
                
    $output '<form action="cart.php?action=update" method="post" id="cart">
                <table>'
    ;
                foreach (
    $this->Cart as $ProductID => $Qty){
                    
    $result $Database->query('SELECT * FROM books WHERE id = '.$ProductID);
                    
    $row $result->fetch();
                    
    $price sprintf('&pound;%.2f'$row['price']);
                    
    $rowTotal sprintf('&pound;%.2f'$row['price'] * $Qty);
                    
    $total += $row['price'] * $Qty;
                    
    $output .= <<<ROW
                    <tr>
                        <td>
                            <a href="cart.php?action=delete&id=
    {$ProductID}" class="r">Remove</a>
                        </td>
                        <td>
    {$row['title']} by {$row['author']}</td>
                        <td>
    {$price}</td>
                        <td>
                            <input type="text" name="product[
    {$ProductID}]" value="{$Qty}" size="3" maxlength="3" />
                        </td>
                        <td>
    {$rowTotal}</td>
                    </tr>
    ROW;
                }
                
    $total sprintf('&pound;%.2f'$total);
                
    $output .= <<<END
                </table>
                <p>Grand total: <strong>
    {$total}</strong></p>
                <div><button type="submit">Update cart</button></div>
            </form>
    END;
                return 
    $output;
            }
        }
        function 
    Message() {
            
    $count $this->NumberOfItems();
            if(
    $count == 0)    $count 'no';
            
    $s = ($count == 1) ? '' 's';
            return 
    '<p>You have <a href="cart.php">' $this->NumberOfItems() . ' item' $s ' in your shopping cart</a></p>';
        }
    }
    Then, in cart.php:
    PHP Code:
    session_start();
    include('cart.class.php');
    function ValueOrNull($Key, $Array){
        return Array_Key_Exists($Key, $Array) ? $Array[$Key] : null;
    }
    $Cart = Cart::ConstructFromSession();
    $ProductID = ValueOrNull('id', $_GET);
    $Qty = ValueOrNull('qty', $_GET);
    switch ($_GET['action']) {
        case 'add':
            $Cart->Add($ProductID, $Qty);
            break;
        case 'delete':
            $Cart->Remove($ProductID);
            break;
        case 'update':
            foreach($_POST['product'] as $ProductID => $Qty){
                $Cart->SetQty($ProductID, $Qty);
            }
        break;
    }
    ?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
        <head>
            <title>PHP Shopping Cart Demo · Cart</title>
            <link rel="stylesheet" href="css/styles.css" />
        </head>
        <body>
            <div id="shoppingcart">
                <h1>Your Shopping Cart</h1>
                <?php echo $Cart->Message(); ?>
            </div>
            <div id="contents">
                <h1>Please check quantities...</h1>
                <?php echo $Cart->Render($db); ?>
                <p><a href="index.php">Back to bookshop...</a></p>
            </div>
        </body>
    </html>
    So, to create a Cart object from session, simply use Cart::ConstructFromSession();

    If you want multiple carts in the session, give that function a string, which will assign an array in the session for it specially and you can then access it.

    Using the object variable returned from this (e.g. $Cart, using $Cart = Cart::ConstructFromSession() ):
    • Use $Cart->Add($ProductID, $Qty = 1) to add a product with that ID and Quantity. If the product already exist, the qty will add to the existing value. Not putting a second parameter will assume a value of 1
    • Use $Cart->SetQty($ProductID, $Qty = 1) to add a product with that ID and Quantity. If the product already exists, the qty will overwrite the existing value. Not putting a second parameter will assume a value of 1
    • Use $Cart->Remove($ProductID, $Qty = null) to remove a certain product. Without a second parameter, the product will be removed from the cart entirely. With a second parameter, it will remove that number from the quantity of that product.
    • Use $Cart->Exists($ProductID) to find if a product is already in the cart.
    • Use $Cart->Get($ProductID) to grab a pointer to a product in the cart.
    • Use $Cart->NumberOfItems() to get the number of items in the cart.
    • Use $Cart->Render($Database) to output the full cart table.
    • Use $Cart->Message() to output a message about the number of items in the cart.
    Jake Arkinstall
    "Sometimes you don't need to reinvent the wheel;
    Sometimes its enough to make that wheel more rounded"-Molona

  4. #4
    SitePoint Evangelist
    Join Date
    Apr 2007
    Posts
    398
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Wow, thanks much more advanced to what I do!.

    However still having a problem getting the cart going:

    http://www.inspireaway.co.uk/cart/index.php

    It does not seem to add any items. Here's the whole code now, could you kindly advise where i'm going wrong?

    Thanks

    index.php

    PHP Code:

    <?php
    // Include MySQL class
    require_once('**********.php');
    // Include database connection
    require_once('**********.php');
    // Start the session
    session_start();
    ?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
        
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
        <title>PHP Shopping Cart Demo  Bookshop</title>
        <link rel="stylesheet" href="css/styles.css" />
    </head>

    <body>

    <div id="shoppingcart">

    <h1>Your Shopping Cart</h1>

    <?php
    function writeShoppingCart() {
        
    $cart $_SESSION['cart'];
        if (!
    $cart) {
            return 
    '<p>You have no items in your shopping cart</p>';
        } else {
            
    // Parse the cart session variable
            
    $items explode(',',$cart);
            
    $s = (count($items) > 1) ? 's':'';
            return 
    '<p>You have <a href="cart.php">'.count($items).' item'.$s.' in your shopping cart</a></p>';
        }
    }

    echo 
    writeShoppingCart();
    ?>

    </div>

    <div id="booklist">

    <h1>Books In Our Store</h1>

    <?php
    $sql 
    'SELECT * FROM books ORDER BY id';
    $result $db->query($sql);
    $output[] = '<ul>';
    while (
    $row $result->fetch()) {
        
    $output[] = '<li>"'.$row['title'].'" by '.$row['author'].': &pound;'.$row['price'].'<br /></li>
                        <form action="cart.php?action=add&id=&id='
    .$row['id'].'" method="post">
    <select name="qty" id="qty">
     <option selected="selected" value="1">1</option>
     <option value="2">2</option>
     <option value="3">3</option>
     <option value="4">4</option>
     <option value="5">5</option>
     </select>
    <input type="submit" value="Add to Cart" name="submit" />
    </form>

    '
    ;
    }
    $output[] = '</ul>';
    echo 
    join('',$output);
    ?>

    </div>

    </body>
    </html>
    cart.class.php
    PHP Code:
    <?php
    class Cart{
        protected 
    $Cart = array();
        static function 
    ConstructFromSession($CartSessionKey 'cart'){
            if(!
    Array_Key_Exists($CartSessionKey$_SESSION)) $_SESSION[$CartSessionKey] = array();
            return new 
    Cart($_SESSION[$CartSessionKey]);
        }
        function 
    __Construct(array &$Cart){
            
    $this->Cart =& $Cart;
        }
        function 
    Add($ProductID$Qty 1){
            
    $Product =& $this->Get($ProductID);
            
    $Product += (int)$Qty;
            
    $this->Filter();
        }
        function 
    SetQty($ProductID$Qty 1){
            
    $Product =& $this->Get($ProductID);
            
    $Product $Qty;
            
    $this->Filter();
        }
        function 
    Remove($ProductID$Qty null){
            if(
    is_null($Qty)){
                
    $Qty $this->Get($ProductID);
            }
            
    $this->Add($ProductID, -$Qty);
        }
        function 
    Exists($ProductID){
            
    $this->Filter();
            return 
    Array_Key_Exists($ProductID$this->Cart);
        }
        function &
    Get($ProductID){
            if(!
    $this->Exists($ProductID)){ $this->Cart[$ProductID] = 0; }
            return 
    $this->Cart[$ProductID];
        }
        function 
    Filter(){
            foreach(
    $this->Cart as $ProductID => &$Qty){
                if(
    $Qty <= 0) unset($this->Cart[$ProductID]);
            }
        }
        function 
    NumberOfItems(){
            
    $this->Filter();
            return 
    Count($this->Cart);
        }
        function 
    Render($Database){
            if(
    $this->NumberOfItems() == 0){
                return 
    '<p>You shopping cart is empty.</p>';
            }else{
                
    $total 0;
                
    $output '<form action="cart.php?action=update" method="post" id="cart">
                <table>'
    ;
                foreach (
    $this->Cart as $ProductID => $Qty){
                    
    $result $Database->query('SELECT * FROM books WHERE id = '.$ProductID);
                    
    $row $result->fetch();
                    
    $price sprintf('&pound;%.2f'$row['price']);
                    
    $rowTotal sprintf('&pound;%.2f'$row['price'] * $Qty);
                    
    $total += $row['price'] * $Qty;
                    
    $output .= <<<ROW
                    <tr>
                        <td>
                            <a href="cart.php?action=delete&id=
    {$ProductID}" class="r">Remove</a>
                        </td>
                        <td>
    {$row['title']} by {$row['author']}</td>
                        <td>
    {$price}</td>
                        <td>
                            <input type="text" name="product[
    {$ProductID}]" value="{$Qty}" size="3" maxlength="3" />
                        </td>
                        <td>
    {$rowTotal}</td>
                    </tr>
    ROW;
                }
                
    $total sprintf('&pound;%.2f'$total);
                
    $output .= <<<END
                </table>
                <p>Grand total: <strong>
    {$total}</strong></p>
                <div><button type="submit">Update cart</button></div>
            </form>
    END;
                return 
    $output;
            }
        }
        function 
    Message() {
            
    $count $this->NumberOfItems();
            if(
    $count == 0)    $count 'no';
            
    $s = ($count == 1) ? '' 's';
            return 
    '<p>You have <a href="cart.php">' $this->NumberOfItems() . ' item' $s ' in your shopping cart</a></p>';
        }
    }

    ?>
    cart.php

    PHP Code:
    <?php
    // Include MySQL class
    require_once('***********');
    // Include database connection
    require_once('***********');
    // Start the session

    session_start();
    include(
    'cart.class.php');
    function 
    ValueOrNull($Key$Array){
        return 
    Array_Key_Exists($Key$Array) ? $Array[$Key] : null;
    }
    $Cart Cart::ConstructFromSession();
    $ProductID ValueOrNull('id'$_GET);
    $Qty ValueOrNull('qty'$_GET);
    switch (
    $_GET['action']) {
        case 
    'add':
            
    $Cart->Add($ProductID$Qty);
            break;
        case 
    'delete':
            
    $Cart->Remove($ProductID);
            break;
        case 
    'update':
            foreach(
    $_POST['product'] as $ProductID => $Qty){
                
    $Cart->SetQty($ProductID$Qty);
            }
        break;
    }
    ?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
        <head>
            <title>PHP Shopping Cart Demo  Cart</title>
            <link rel="stylesheet" href="css/styles.css" />
        </head>
        <body>
            <div id="shoppingcart">
                <h1>Your Shopping Cart</h1>
                <?php echo $Cart->Message(); ?>
            </div>
            <div id="contents">
                <h1>Please check quantities...</h1>
                <?php echo $Cart->Render($db); ?>
                <p><a href="index.php">Back to bookshop...</a></p>
            </div>
        </body>
    </html>

  5. #5
    SitePoint Wizard lorenw's Avatar
    Join Date
    Feb 2005
    Location
    was rainy Oregon now sunny Florida
    Posts
    1,104
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Cool arkinstall, this is something I can study also.

    I have looked into classes and never understood private, public and static function.

    What would happen to the class if you called your static function public or private or just a plain old function?

    This is what confuses and holds me back.

    Thanks
    What I lack in acuracy I make up for in misteaks

  6. #6
    SitePoint Wizard
    Join Date
    Nov 2005
    Posts
    1,191
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Public/private are a separate concept from static. They refer to the visibility of the function or variable:
    PHP Code:
    class MyClass {
        private function 
    privFunc() {
            echo 
    'private function called';
        }
        public function 
    pubFunc() {
            echo 
    'public function called';
            
    privFunc(); // can call the private function from within the class
        
    }
    }

    $class = new MyClass();
    $class->privFunc(); // won't work as the function is not visible outside the object
    $class->pubFunc(); // prints: public function calledprivate function called 
    By default things are public:
    PHP Code:
    function foo(); // same as public function foo()
    static function foo(); // same as public static function foo() 
    Static methods/variables are tied to the class, not the instance of the class. That is, you don't need to create a new class() to use them.
    PHP Code:
    class MyClass {
        public static function 
    statFunc() {
            echo 
    'static function called';
        }
        public function 
    pubFunc() {
            echo 
    'public function called';
        }
    }

    MyClass::statFunc(); // prints static function called
    // but to use pubFunc an instance is needed
    $class = new MyClass();
    $class->pubFunc(); 
    note the scope resolution operator needed to access statics rather than the usual ->

  7. #7
    Theoretical Physics Student bronze trophy Jake Arkinstall's Avatar
    Join Date
    May 2006
    Location
    Lancaster University, UK
    Posts
    7,062
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    @Chris:

    In index.php, it won't add because the loop you're using to show how many items are in the cart can't work with the way the cart now works.

    So, instead of:
    PHP Code:
    <?php
    function writeShoppingCart() {
        
    $cart $_SESSION['cart'];
        if (!
    $cart) {
            return 
    '<p>You have no items in your shopping cart</p>';
        } else {
            
    // Parse the cart session variable
            
    $items explode(',',$cart);
            
    $s = (count($items) > 1) ? 's':'';
            return 
    '<p>You have <a href="cart.php">'.count($items).' item'.$s.' in your shopping cart</a></p>';
        }
    }
    echo 
    writeShoppingCart();
    ?>
    Use:
    PHP Code:
    <?php
    include('cart.class.php'); //preferably at the top with the other includes.
    $Cart Cart::ConstructFromSession();
    echo 
    $Cart->Message();
    ?>
    As to your problem with adding books, the issue with the form. Look at the URL when you've sent the form, there's no qty and two ID fields. The correct url does add the items:
    Code:
    cart.php?action=add&id=1&qty=4
    I was under the impression that you wanted to do this through $_GET, but as the form is, in fact, $_POST, use this as the form:
    PHP Code:
    <div id="booklist">
    <h1>Books In Our Store</h1>
    <?php
    $sql 
    'SELECT * FROM books ORDER BY id';
    $result $db->query($sql);
    $output '<ul>';
    while (
    $row $result->fetch()) {
        
    $output .= <<<ITEM
            <li>
                "
    {$row['title']}" by {$row['author']}: &pound;{$row['price']}
                <br />
               <form action="cart.php?action=add" method="post">
                   <input type="hidden" name="id" value="
    {$row['id']}" />
                   <select name="qty" id="qty">
                       <option selected="selected" value="1">1</option>
                       <option value="2">2</option>
                       <option value="3">3</option>
                       <option value="4">4</option>
                       <option value="5">5</option>
                   </select>
                   <input type="submit" value="Add to Cart" name="submit" />
               </form>
           </li>
    ITEM;
    }
    $output .= '</ul>';
    echo 
    $output;
    ?>
    </div>
    Cart.php:
    PHP Code:
    $ProductID ValueOrNull('id'$_POST);
    $Qty ValueOrNull('qty'$_POST); 
    Jake Arkinstall
    "Sometimes you don't need to reinvent the wheel;
    Sometimes its enough to make that wheel more rounded"-Molona

  8. #8
    SitePoint Evangelist
    Join Date
    Apr 2007
    Posts
    398
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    That's fantastic Arkinstall. I'm going to try and get my head around what you've done and add some more features.

  9. #9
    SitePoint Evangelist
    Join Date
    Apr 2007
    Posts
    398
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Sorry to be a pain, but one thing I can't seem to get my head around though is when you order an item and hit refresh:

    ie:

    Code:
    cart.php?action=add&id=1&qty=4
    If say one item already has four ordered, if you hit refresh then that order becomes 8.

  10. #10
    Theoretical Physics Student bronze trophy Jake Arkinstall's Avatar
    Join Date
    May 2006
    Location
    Lancaster University, UK
    Posts
    7,062
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    That would happen, because the session would be updated.

    One option is to use:
    PHP Code:
    if(count($_GET) > 0){
        
    header('location: cart.php');
        exit;

    After the switch statement. That way, they will be relocated to the plain cart without commands in the URL, so refreshing would have no effect.
    Jake Arkinstall
    "Sometimes you don't need to reinvent the wheel;
    Sometimes its enough to make that wheel more rounded"-Molona

  11. #11
    SitePoint Evangelist
    Join Date
    Apr 2007
    Posts
    398
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi arkinstall,

    Thanks again for your help. I've been reading up on functions, classes etc in the manual to try and understand this a bit better, and is something I defo want to learn.

    However I still have two problems.

    The first being the number of items in my cart. Say I order 4 of the first product and 3 of the second the total (7) ONLY shows a distinct number 2 I tried changing a few things trying to keep hold of the $Qty value each time, but to no avail.

    PHP Code:
        function Message() { 
            
    $count $this->NumberOfItems(); 
            if(
    $count == 0)    $count 'no'
            
    $s = ($count == 1) ? '' 's'
            return 
    '<p>You have <a href="cart.php">' $this->NumberOfItems() . ' item' $s ' in your shopping cart</a></p>'
        } 

    And the other thing is since I moved from $_GET to $POST I can no longer remove an item:

    PHP Code:
    $ProductID ValueOrNull('id'$_POST);
    $Qty ValueOrNull('qty'$_POST); 
    PHP Code:
      <a href="cart.php?action=delete&id={$ProductID}class="r">Remove</a
    Would you be kind enough to help me with these last two problems?

  12. #12
    Theoretical Physics Student bronze trophy Jake Arkinstall's Avatar
    Join Date
    May 2006
    Location
    Lancaster University, UK
    Posts
    7,062
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    For the first issue, add this to your class definition:
    PHP Code:
    function TotalNumberOfItems(){
        return 
    array_sum($this->Cart);

    And use $Cart->TotalNumberOfItems() to get the TOTAL amount of items, not the distinct amount.

    As for your second question, you can do one of two things. One is to keep your passing method constant - either post or get, and apply it to everything, e.g. using a form instead to send it with POST, or channel everything through GET (which, being a cart system, I'd recommend). Second solution would be to send $_REQUEST to the class initialization rather that $_POST or $_GET, though I don't usually recommend the use of $_REQUEST, I suppose it has a place here.
    Jake Arkinstall
    "Sometimes you don't need to reinvent the wheel;
    Sometimes its enough to make that wheel more rounded"-Molona

  13. #13
    SitePoint Evangelist
    Join Date
    Apr 2007
    Posts
    398
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi,

    Been playing with this over the last week or so and learning things so I understand it a bit better and i'm trying to do one thing.

    In some cases books will be paperback, hardback or binded.

    Now what i've done is say if a book can be like this (which it won't always be) output a dropdown menu beside it.

    PHP Code:
    <div id="booklist">
    <h1>Books In Our Store</h1>
    <?php
    $sql 
    'SELECT * FROM books ORDER BY id';
    $result $db->query($sql);
    $output '<ul>';
    while (
    $row $result->fetch()) {

    // if size = 0 output the type of book dropdown
    $style = ( $row['size'] == "0" ) ? 
         
    "<select name=\"style\" id=\"style\">
            <option selected=\"selected\" value=\"Paperback\">Paperback</option>
            <option value=\"Hardback\">Hardback</option>
            <option value=\"Binded\">Binded</option>
           </select>" 
    "";

        
    $output .= <<<ITEM
            <li>
                "
    {$row['title']}" by {$row['author']}: &pound;{$row['price']}
                <br />
               <form action="cart.php?action=add" method="post">
                   <input type="hidden" name="id" value="
    {$row['id']}" />
                   <select name="qty" id="qty">
                       <option selected="selected" value="1">1</option>
                       <option value="2">2</option>
                       <option value="3">3</option>
                       <option value="4">4</option>
                       <option value="5">5</option>
                   </select>
                  
    $style
                   <input type="submit" value="Add to Cart" name="submit" />
               </form>
           </li>
    ITEM;
    }
    $output .= '</ul>';
    echo 
    $output;
    ?>
    Now this works fine, but is there anyway I could take this option and place it before the title in cart.php i.e:

    Paperback: {$row['title']} :
    and then show the quantity (1) in cart.php

    and then if they went back to the store and added a second paperback copy for the same book the quantity would become (2)

    But if they ordered that book in hardback a new item would be added to cart.php like:

    Hardback: {$row['title']}

    despite it being the same item, but a different book style?

    Is that possible?

    Thanks


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •