10 Replies - 17207 Views - Last Post: 16 March 2012 - 08:05 AM Rate Topic: -----

#1 hathead1990  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 27
  • Joined: 25-November 11

HELP! PHP mini cart not working :(

Posted 13 March 2012 - 05:03 PM

Hi all I have followed a tutorial on-line but I have errors in the code (as per usually with tutorials, but im a beginner so I cant complain)Tutorial below.
PHP MINI CART TUTORIAL

I have a cart.php page and a functions.php page taken from the website above.

On my products page the items show up fine and I can click on a product and this gets sent to the cart and adds the item but does not display anything else. The problem is displaying the products selected so that I can then see the price etc of all the products selected in the basket! Please note that the cart page does echo how many items are in the basket but thats it.

Thank you in advance I know there is a lot of information but I am sure someone can help me.

Sorry forgot to add the errors.... :online2long:

Notice: Undefined index: action in I:\www\Application\cart.php on line 11
Your Shopping Cart

You have 10 items in your shopping cart

Please check quantities...

Notice: Undefined variable: product_id in I:\www\Application\include\functions.inc.php on line 26

Fatal error: Call to a member function query() on a non-object in I:\www\Application\include\functions.inc.php on line 27

cart.php
<?php
include('include/db_config.php');
// Include functions
include('include/functions.inc.php');
// Start the session

session_start();
// Process actions

$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>
	
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
	<title>Cart</title>
</head>

<body>

<h1>Your Shopping Cart</h1>

<?php
echo writeShoppingCart();
?>

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

<?php
echo showCart();
?>

<p><a href="products.php">Back to Products Listing...</a></p>

</div>

</body>
</html>



functions.inc.php
<?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>';
	}
}

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 : 1;
		}
		$output[] = '<form action="cart.php?action=update" method="post" id="cart">';
		$output[] = '<table>';
		foreach ($contents as $id=>$qty) {
			$sql = 'SELECT * FROM products WHERE id = '.$product_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);
}
?>


This post has been edited by Atli: 14 March 2012 - 08:51 AM
Reason for edit:: Please post your code inside the post, within [code] tags, instead of attaching it as a text file.


Is This A Good Question/Topic? 0
  • +

Replies To: HELP! PHP mini cart not working :(

#2 xxxjj18  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 53
  • View blog
  • Posts: 167
  • Joined: 30-November 11

Re: HELP! PHP mini cart not working :(

Posted 14 March 2012 - 04:47 AM

Can you upload the db file so I can see what went wrong there?

Anyways, the error on line 11 is due to $_GET["action"] not being defined; you should incorporate a code to prevent this, something like:

$action = isset($_GET['action']) ? $_GET['action'] : "home";



And have the 'home' action go to the index; something like that.

On line 26 in the functions.inc.php file, $product_id is never defined; not in either of the two files above.

The last error (line 27) occurs because you never instantiated the $db object; something like:

$db = new ClassNameForDatabase();



Therefore you're trying to call a function from a non-object; because $db was never actually created as an object.

Does this answer your question?
Was This Post Helpful? 2
  • +
  • -

#3 hathead1990  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 27
  • Joined: 25-November 11

Re: HELP! PHP mini cart not working :(

Posted 14 March 2012 - 04:21 PM

Sorry it took me so long to reply. I have uploaded the db_config. I managed to fix the action error! But struggling with the other (same) errors. Cheers

<?php 
$hostname='localhost'; 
$user='root'; 
$pass=''; 
$dbase='members'; 
$connection = mysql_connect("$hostname" , "$user" , "$pass") 
or die ("Can't connect to MySQL");
$db = mysql_select_db($dbase , $connection) or die ("Can't select database, Check connection settings or server status.");
?>


Was This Post Helpful? 0
  • +
  • -

#4 Atli  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 3718
  • View blog
  • Posts: 5,989
  • Joined: 08-June 10

Re: HELP! PHP mini cart not working :(

Posted 14 March 2012 - 04:30 PM

hathead1990, please don't attach your code to the post. Put it inside the post, within [code] tags. It's far easier for people to access it that way.

Also, there is really no point quoting the entire post above yours.
Was This Post Helpful? 0
  • +
  • -

#5 hathead1990  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 27
  • Joined: 25-November 11

Re: HELP! PHP mini cart not working :(

Posted 14 March 2012 - 04:32 PM

Got all other errors sorted apart from the one below any help?

Fatal error: Class 'ClassNameForDatabase' not found in www\Application\include\functions.inc.php on line 30



This is how the cart is meant to look if thats any help

CART

This post has been edited by hathead1990: 14 March 2012 - 04:33 PM

Was This Post Helpful? 0
  • +
  • -

#6 xxxjj18  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 53
  • View blog
  • Posts: 167
  • Joined: 30-November 11

Re: HELP! PHP mini cart not working :(

Posted 14 March 2012 - 05:25 PM

Lol, you weren't actually supposed to use that name for your database class; that's just a generic name I made up for an example.

And in your db file you created the $db variable but this still does not make it an object that has the function query; you have to create this method manually.

Also, did you create the $product_id variable yet?

I see what you're getting at with the "$db->query", but the correct code for this would be:

$sql = "SELECT * FROM `RandomTableName` WHERE `id` = 1";
$res = mysql_query($sql,$con) or die(mysql_error()); //Use your DB connection for $con

if($res) {
  //Query successfuly
}



If you have any concerns on the mysql_query method, please visit here.

Does this help?
Was This Post Helpful? 0
  • +
  • -

#7 hathead1990  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 27
  • Joined: 25-November 11

Re: HELP! PHP mini cart not working :(

Posted 15 March 2012 - 01:17 PM

lol. I might just commit suicide now. I now have a mysql.class.php file which I have uploaded if this helps but I still dont have a clue what to do next.


Do you know of any other mini carp tutorials on the net that actually work lol.

Cheers and thanks for your help.

Attached File(s)


Was This Post Helpful? 0
  • +
  • -

#8 RudiVisser  Icon User is offline

  • .. does not guess solutions
  • member icon

Reputation: 1003
  • View blog
  • Posts: 3,562
  • Joined: 05-June 09

Re: HELP! PHP mini cart not working :(

Posted 15 March 2012 - 01:36 PM

http://uk3.php.net/tut.php is a good place to start
Was This Post Helpful? 1
  • +
  • -

#9 JackOfAllTrades  Icon User is offline

  • Saucy!
  • member icon

Reputation: 6058
  • View blog
  • Posts: 23,496
  • Joined: 23-August 08

Re: HELP! PHP mini cart not working :(

Posted 16 March 2012 - 02:40 AM

Stop trying to just cobble something together from copied and pasted code -- without making an attempt to understand even the basics -- and LEARN THE LANGUAGE!
Was This Post Helpful? 1
  • +
  • -

#10 hathead1990  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 27
  • Joined: 25-November 11

Re: HELP! PHP mini cart not working :(

Posted 16 March 2012 - 07:47 AM

Hi again all. I managed to work my way though you tube videos starting from the bottom up!

Thankfully after some patience I managed to get the cart working however. Attached code

<?php

	$product_id = $_GET['id'];	 //the product id from the URL 
	$action 	= $_GET['action']; //the action from the URL 

	//if there is an product_id and that product_id doesn't exist display an error message
	if($product_id && !productExists($product_id)) {
		die("Error. Product Doesn't Exist");
	}

	switch($action) {	//decide what to do	
	
		case "add":
			$_SESSION['cart'][$product_id]++; //add one to the quantity of the product with id $product_id 
		break;
		
		case "remove":
			$_SESSION['cart'][$product_id]--; //remove one from the quantity of the product with id $product_id 
			if($_SESSION['cart'][$product_id] == 0) unset($_SESSION['cart'][$product_id]); //if the quantity is zero, remove it completely (using the 'unset' function) - otherwise is will show zero, then -1, -2 etc when the user keeps removing items. 
		break;
		
		case "empty":
			unset($_SESSION['cart']); //unset the whole cart, i.e. empty the cart. 
		break;
	
	}
	
?>


<?php	

	if($_SESSION['cart']) {	//if the cart isn't empty
		//show the cart
		
		echo "<table border=\"1\" padding=\"3\" width=\"40%\">";	//format the cart using a HTML table
		
			//iterate through the cart, the $product_id is the key and $quantity is the value
			foreach($_SESSION['cart'] as $product_id => $quantity) {	
				
				$sql = sprintf("SELECT title, artist, price FROM products WHERE id = %d;",
								$product_id); 
					
				$result = mysql_query($sql);
					
				//Only display the row if there is a product (though there should always be as we have already checked)
				if(mysql_num_rows($result) > 0) {
				
					list($title, $artist, $price) = mysql_fetch_row($result);
				
					$line_cost = $price * $quantity;		//work out the line cost
					$total = $total + $line_cost;			//add to the total cost
				
					echo "<tr>";
						//show this information in table cells
						echo "<td align=\"center\">$title</td>";
						echo "<td align=\"center\">$artist</td>";
						//along with a 'remove' link next to the quantity - which links to this page, but with an action of remove, and the id of the current product
						echo "<td align=\"center\">$quantity <a href=\"$_SERVER[PHP_SELF]?action=remove&id=$product_id\">Remove</a></td>";
						echo "<td align=\"center\">$line_cost</td>";
					
					echo "</tr>";
					
				}
			
			}
			
			//show the total
			echo "<tr>";
				echo "<td colspan=\"2\" align=\"right\">The Total Is</td>";
				echo "<td align=\"right\">$total</td>";
			echo "</tr>";
			
			//show the empty cart link - which links to this page, but with an action of empty. A simple bit of javascript in the onlick event of the link asks the user for confirmation
			echo "<tr>";
				echo "<td colspan=\"3\" align=\"right\"><a href=\"$_SERVER[PHP_SELF]?action=empty\" onclick=\"return confirm('Are you sure?');\">Empty Cart</a></td>";
			echo "</tr>";		
		echo "</table>";
		
		
	
	}else{
		//otherwise tell the user they have no items in their cart
		echo "No items in you cart.";
		
	}
	
	//function to check if a product exists
	function productExists($product_id) {
			//use sprintf to make sure that $product_id is inserted into the query as a number - to prevent SQL injection
			$sql = sprintf("SELECT * FROM products WHERE id = %d;",
							$product_id); 
				
			return mysql_num_rows(mysql_query($sql)) > 0;
	}
?>

<a href="products.php">Continue Shopping</a>



However I keep receiving these errors. I cant spot the problem after looking at the code. Maybe someone will! (Just a note 13 meaning the quantity).

Notice: Undefined index: 13 in I:\cart.php on line 61

Notice: Undefined variable: total in I:\cart.php on line 99
Was This Post Helpful? 0
  • +
  • -

#11 hathead1990  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 27
  • Joined: 25-November 11

Re: HELP! PHP mini cart not working :(

Posted 16 March 2012 - 08:05 AM

:)

This post has been edited by hathead1990: 16 March 2012 - 08:07 AM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1