Shopping Cart Class [probleem: product toevoegen en Cart laten zien]

Overzicht Reageren

Sponsored by: Vacatures door Monsterboard

Ryan L

Ryan L

18/05/2011 21:19:02
Quote Anchor link
Hallo,

ik heb deze Shopping Cart Class gevonden maar nou lukt het me niet om een product page te maken waar je op "add to cart" kan klikken waarna een _POST gestuurd wordt naar dezelfde product page en dmv een if statement de method cart_add_item() wordt geroepen.

ik krijg de volgende foutmelding waneer ik naar de product page ga:
Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given in ../public/cart.php on line 261

Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given in ../public/cart.php on line 261

En wanneer ik op add to cart klik:

Fatal error: Cannot use object of type cart as array in ..public/cart.php on line 108

Kan iemand mij uitleggen wat er verkeerd is en hoe ik dit kan oplossen?
alvast bedankt.

dit is de class die ik gebruik
Quote:
Code (php)
PHP script in nieuw venster Selecteer het PHP script
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
<?php
/**
* Shopping Cart Class
*
* @author Ben Barnett <[email protected]>
*/
    
    
/**
* Shopping Cart Class
*
* This module is a shopping cart class with add/edit/delete product functionality.
* Each item is stored in a session variable as an array with the productID being the key
* and the quantitly of the item as the value. The cookie stores the serialized cart contents
* between visits.
* IMPORTANT NOTE: The show_cart function
* outputs a very bland table so you will need to edit this to beautify it.

*/

class cart
{
    
    /**
    * The expiry time for the cart cookie
    */

    var $expire = 3600;
    
    
    var
$del_cookie = -1;
    
    /**
    * Class constructor
    *
    * Start the session, if the cart doesn't exist as a session variable, check for a cookie,
    * if the cookie isn't there, make a new cart.
    */

    function cart()
    {

    // Start the session.
    //session_start();

    
    $time = time();
    $this->expire = $time + $this->expire;
    
    // If the session variables haven't been registered yet, do that now.
    if(!isset($_SESSION['cart']))
        {

        
        if(isset($_COOKIE['cart']))
            {

            $_SESSION['cart'] = array();
            $_SESSION['cart'] = unserialize(stripslashes($_COOKIE['cart']));
            $_SESSION['total_items'] = $this->cart_calculate_items($_SESSION['cart']);
            $_SESSION['total_price'] = $this->cart_calculate_price($_SESSION['cart']);
            }

        else
            {
            $_SESSION['cart'] = array();
            $_SESSION['total_items'] = 0;
            $_SESSION['total_price'] = 0.00;
            
            $s_cart = serialize($_SESSION['cart']);
            setcookie('cart', $s_cart, $this->expire);
            }
        }
    

    }

    
    
    
    /**
    * Displays the cart
    *
    * @param array $cart The cart you want to display.
    * @param boolean $pictures Show pictures in cart? (default=false)
    * @param boolean $editable Is cart editable? (default=true)
    */

    function cart_show($cart, $pictures = 'false', $editable = 'true')
    {

//    require($_SERVER['DOCUMENT_ROOT'].'/path/to/database/connection_code.php');
//    mysql_select_db($database_connAT, $connAT);

    echo "<table border=\"1\"><tr><td>Product</td><td>Quantity</td><td>Price</td></tr>\n";
    foreach($cart as $productID => $qty)
        {

        $product = $this->cart_get_item_details($productID);
        echo "<tr>\n";
        echo "<td>".$product['details']."</td><td>".$qty."</td><td>&pound;".$product['price']."</td>\n";
        echo "</tr>\n";
        }

    echo '</table>';
    }


    
    
    /**
    * Adds an item to the cart.
    *
    * If the item is already in the cart, it increments the quantity by one.
    * Otherwise, it adds one of the selected item to the cart. It then recalculates
    * the number of items in the cart and the total cost.
    *
    * @param string $item The productID to be added.
    */

    function cart_add_item($item)
    {

    // If cart item exists, increment it by one...
    if(isset($_SESSION['cart'][$item]))
        {

        $_SESSION['cart'][$item]++;
        
        }

        
    // ...otherwise add it as a new item.
    else
        {
        $_SESSION['cart'][$item] = 1;
        }

    
    // Recalculate totals
    $_SESSION['total_items'] = $this->cart_calculate_items($_SESSION['cart']);
    $_SESSION['total_price'] = $this->cart_calculate_price($_SESSION['cart']);
    $s_cart = serialize($_SESSION['cart']);
    setcookie('cart', $s_cart, $this->expire);
    }


    
    
    /**
    * Removes a product from the cart.
    *
    * Removes a product totally from the cart by unsetting it's key and value
    * from the session array.
    */

    function cart_delete_item($productID)
    {

    // Unset product variable
    unset($_SESSION['cart'][$productID]);
    
    // Recalculate totals
    $_SESSION['total_items'] = $this->cart_calculate_items($_SESSION['cart']);
    $_SESSION['total_price'] = $this->cart_calculate_price($_SESSION['cart']);
    $s_cart = serialize($_SESSION['cart']);
    setcookie('cart', $s_cart, $this->expire);
    }


    
    /**
    * Edits the number of each item in the cart
    *
    * If the number is set to zero, remove the item by unsetting the session variable. If
    * the number is anything else, set it the that number.
    *
    * @todo I'm not sure if this function needs any parameters passed to it to work
    * so if it doesn't, this could be why.
    */

    function cart_edit_item()
    {

    // Make sure the variables are being POSTed
    if(isset($_POST['update']))
        {

        foreach($_SESSION['cart'] as $productID => $qty)
            {

            if($_POST['$productID'] ==  0)
                {

                unset($_SESSION['cart'][$productID]);
                }

            else
                {
                $_SESSION['cart'][$productID] = $_POST['productID'];
                }
            }
        }

    // Recalculate totals
    $_SESSION['total_items'] = $this->cart_calculate_items($_SESSION['cart']);
    $_SESSION['total_price'] = $this->cart_calculate_price($_SESSION['cart']);
    $s_cart = serialize($_SESSION['cart']);
    setcookie('cart', $s_cart, $this->expire);
    }

    
    
    
    /**
    * Calculates the number of items in the cart.
    *
    * Calculates the number of items in the cart by looping through the cart incrementing
    * the number of items for each product.
    *
    * @param array $cart The cart to count items in.
    * @return integer The number of items in the cart.
    */

    function cart_calculate_items($cart)
    {

    // Initialise variable to default value
    $items = 0;
    
    // Make sure the cart is actully an array!
    if(is_array($cart))
        {

        // Loop through the cart and add the quanity of each item the the total
        foreach($_SESSION['cart'] as $productID => $qty)
            {

            $items += $qty;
            }
        }

    // Return the total number of items
    return $items;
    }

    
    
    
    /**
    * Calculates the total price of the cart contents.
    *
    * This function is one of the slowest in this application
    * as it has a long database query to carry out and total up.
    *
    * @param array $cart The cart to total the price in.
    * @return float The total price of cart contents.
    */

    function cart_calculate_price($cart)
    {

    // Initialise variable to default value
    $price = 0.00;
    
    // Make sure the cart is actully an array!
    if(is_array($cart))
        {

        
        /**
        * Require the database connection for finding prices.
        */
//        require($_SERVER['DOCUMENT_ROOT'].'/path/to/database/connection_code.php');
//        mysql_select_db($database_connAT, $connAT);
        
        // Loop through the cart array matching prices to products

        foreach($cart as $productID => $qty)
            {

            $query = "SELECT price FROM products WHERE id='$productID'";
            $result = mysql_query($query);
            
            // Then adding the (item price * quantity) to the total price
            //  and starting the loop again

            if($result)
                {

                $row_result = mysql_fetch_assoc($result);
                $item_price = $row_result['price'];
                $price += $item_price*$qty;
                }
            }
        }

    // Return the total price
    return $price;
    }
    
    
    function
cart_get_item_details($productID)
        {

        $query = "SELECT * FROM products WHERE id='$productID'";
        $result = mysql_query($query);
        $row_result = mysql_fetch_assoc($result);
        return $row_result;
        }
    
}

?>


Dit is de product page:
Quote:
Code (php)
PHP script in nieuw venster Selecteer het PHP script
1
<?php require_once("cart.php") ?>

Code (php)
PHP script in nieuw venster Selecteer het PHP script
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<?php
session_start();      // start the session


$cart =& $_SESSION['cart']; // point $cart to session cart.
if(!is_object($cart)) $cart = new Cart(); // if $cart ( $_SESSION['cart'] ) isn't an object, make a new cart

// end of header stuff

// Usually you would get your products from a database but we'll pretend..


$products = array();
$products[1] = array("id"=>1,"name"=>"A Bar of Soap","price"=>2.00);
$products[2] = array("id"=>2,"name"=>"Shampoo","price"=>4.80);
$products[3] = array("id"=>3,"name"=>"Pizza","price"=>12.95);


// check to see if any items are being added
if(isset($_POST['add'])) {
    $product = $_POST['id'];
    $cart->cart_add_item($product['id']);
}



// add product
echo "<table>";
foreach($products as $product) {
    echo "<tr><td><form method='post' action='demo.php'>";
    echo "<input type='hidden' name='id' value='".$product['id']."'/>";
    echo "".$product['name'].' $'.number_format($product['price'],2)." ";
    echo "<input type='text' name='qty' size='5' value='1'><input type='submit' value='Add to cart' name='add'>";
    echo "</form></td></tr>";
}

echo "</table>";


echo "<h2>Items in cart</h2>";

$cart->cart_show($cart);

?>
 
Er zijn nog geen reacties op dit bericht.



Overzicht Reageren

 
 

Om de gebruiksvriendelijkheid van onze website en diensten te optimaliseren maken wij gebruik van cookies. Deze cookies gebruiken wij voor functionaliteiten, analytische gegevens en marketing doeleinden. U vindt meer informatie in onze privacy statement.