Jump to content

Recommended Posts

Hello, first off, I don't have a lot of programming experience. I am working off a YouTube tutorial...

 

I am working with a simple PHP/MYSQL shopping cart that only supports one category and a Paypal checkout/add to cart button. My index.php page successfully shows the items that are in the database with the products() function. I have another function that shows the carts contents, cart(). That successfully displays the carts contents, if available.

 

What I am trying to do is create another function cart_qty() to break apart the contents of cart() to see how many items there are. I would like to display, "You have 1 item" or "...2 items", ect.

 

Any thoughts or helpful direction would be awesome!

 

index.php

<?php

require 'cart.php';

?>
<!DOCTYPE html>
<head>
</head>
<body>
	<div class="container"><!-- start container -->
		<div class="sixteen columns">
			<h1 class="remove-bottom" style="margin-top: 40px">Test Shpping Cart </h1>
			<hr />
		</div>
        <div id="products" class="two-thirds column">
            <h1>Products In Our Store</h1>
            <?php
            echo products();
            ?>
        </div>
        <div id="shoppingcart" class="one-third column">
            <h3>Your Cart</h3>
            <?php
            echo cart();
            ?>
        <br>
        <br>
        <br>
            <?php
            echo cart_qty();
            ?>
        </div>
	</div><!-- end container -->
</body>
</html>

cart.php

<?php


	// Start the session
	session_start();
	//session_destroy();
	//error_reporting(0);
	
	$page = 'index.php';
	
	mysql_connect('localhost', 'root', '') or die(mysql_error());
	mysql_select_db('cart') or die(mysql_error());
	
	
	// add item to cart
	if (isset($_GET['add'])) {
		$quantity = mysql_query('SELECT id, quantity FROM tblProducts WHERE id=' . mysql_real_escape_string((int)$_GET['add']));  //prevents SQL injections
		while($quantity_row = mysql_fetch_assoc($quantity)) {
			if($quantity_row['quantity'] != $_SESSION['cart_' . (int)$_GET['add']]) {
				$_SESSION['cart_' . (int)$_GET['add']] += '1';
			}
		}
		header('Location: ' . $page);
	}
	
	
	// remove one item from cart
	if (isset($_GET['remove'])) {
		$_SESSION['cart_' . (int)$_GET['remove']] --;
		header('Location: ' . $page);
	}
	
	
	// delete item item from cart
	if (isset($_GET['delete'])) {
		$_SESSION['cart_' . (int)$_GET['delete']] = '0';
		header('Location: ' . $page);
	}
	
	
	// display list of products
	function products() {
		$get = mysql_query('SELECT id, name, description, price, shipping FROM tblProducts WHERE quantity > 0 ORDER BY id ASC');
		
		if (mysql_num_rows($get) ==0) {
			echo 'There are no products to display!';
		} else {
			while($get_row = mysql_fetch_assoc($get)) {
				echo '<p>' . $get_row['name'] . '<br>' . $get_row['description'] . '<br>' . number_format($get_row['price'], 2) . '<br>' . $get_row['shipping'] . '<br><a href="cart.php?add=' . $get_row['id'] . '">Add</a></p>';
			}
		}
	}
	
	
	//generate inputs required by PayPal
	function paypal_items() {
		$num = 0;
		foreach($_SESSION as $name => $value) {
			if($value != 0) {
				if(substr($name, 0, 5) == 'cart_') {
					$id = substr($name, 5, strlen($name)-5);
					$get = mysql_query('SELECT id, name, price, shipping FROM tblProducts WHERE id=' . mysql_real_escape_string((int)$id));  //prevents SQL injections
					while($get_row = mysql_fetch_assoc($get)) {
						$num++;
						echo '<input type="hidden" name="item_number_' . $num . '" value="' . $id . '">';
						echo '<input type="hidden" name="item_name_' . $num . '" value="' . $get_row['name'] . '">';
						echo '<input type="hidden" name="amount_' . $num . '" value="' . $get_row['price'] . '">';
						echo '<input type="hidden" name="shipping_' . $num . '" value="' . $get_row['shipping'] . '">';
						echo '<input type="hidden" name="shipping2_' . $num . '" value="' . $get_row['shipping'] . '">';
						echo '<input type="hidden" name="quantity_' . $num . '" value="' . $value . '">';
					}
				}
			}
		}
	}
	
	//display how many items are in the cart
	function cart() {
		foreach($_SESSION as $name => $value) {
			if($value>0) {
				if(substr($name, 0, 5) == 'cart_') {
					
					//get exact number after "'cart_'$id"
					$id = substr($name, 5, (strlen($name)-5));
					//echo $id;
					
					$get = mysql_query('SELECT id, name, price FROM tblProducts WHERE id=' . mysql_real_escape_string((int)$id));  //prevents SQL injections
					while($get_row = mysql_fetch_assoc($get)) {
						$sub = $get_row['price'] * $value;
						echo $get_row['name'] . ' x ' . $value . ' @ $' . number_format($get_row['price'], 2) . ' = $' .  number_format($sub, 2) . '<a href="cart.php?remove=' . $id .'">-</a> <a href="cart.php?add=' . $id .'">+</a> <a href="cart.php?delete=' . $id .'">delete</a><br>';
					}
				}
				$total += number_format($sub, 2);
			} 
		}
		if ($total == 0) {
			echo "Your cart is empty.";
		} 
		else {
			echo 'Total: $' . number_format($total, 2) . '';
			?>
			<form target="paypal" action="https://www.paypal.com/cgi-bin/webscr" method="post">
				<input type="hidden" name="cmd" value="_cart">
				<input type="hidden" name="upload" value="1">
				<input type="hidden" name="business" value="someone@yahoo.com">
				<?php paypal_items(); ?>
				<input type="hidden" name="currency_code" value="USD">
				<input type="hidden" name="bn" value="PP-ShopCartBF:btn_cart_LG.gif:NonHosted">
				<input type="image" src="https://www.paypalobjects.com/en_US/i/btn/btn_cart_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!">
	<img alt="" border="0" src="https://www.paypalobjects.com/en_US/i/scr/pixel.gif" width="1" height="1">
			</form>		
			<?php
		}
	}


	function cart_qty() {
		///how many items are in cart
	}
	
?>

Link to comment
https://forums.phpfreaks.com/topic/279439-simple-shopping-cart/
Share on other sites

while this doesn't directly address your question, it will make the answer take just one line of code.

 

the definition of your $_SESSION based cart should be changed and simplified to directly support the operations you need to perform on the data.

 

using [cart_id] as the array index requires extra processing for every reference you make to the cart entries.

 

you need to use an array $_SESSION['cart'] that holds an entry for each id - $_SESSION['cart'][id] = qty;

 

to get a count of the different items (id's) in the cart, just use - count($_SESSION['cart'])

 

to get the quantity of all items in the cart, just use - array_sum($_SESSION['cart'])

 

by changing the cart definition to this, you will also simplify most of the code you currently have to just a line or two to manipulate any entry in the cart.

 

also, in your cart() function, you should not run a select query inside of a loop (due to the perform hit). you should get all the item id's at one time and run one query (using a WHERE id IN( ... ) statement) to get all the information about those items in one query. the cart definition i have suggested would let you do this easily as well using  - array_keys($_SESSION['cart'])

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.