Shiopping Cart Help

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

stantheman
Forum Commoner
Posts: 38
Joined: Wed May 26, 2004 8:57 am

Shiopping Cart Help

Post by stantheman »

edit patrikG: USE

Code: Select all

-tags when posting PHP-code!  [/color]

I'm trying to get this sample shopping cart to work but i keep getting these few errors here is my code i bolding the code below so you can find it easier

Warning: mysql_fetch_row(): supplied argument is not a valid MySQL result resource in c:\inetpub\wwwroot\unnamed site 1\cart.php on line 45


Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in c:\inetpub\wwwroot\unnamed site 1\cart.php on line 154
 
//db.php

Code: Select all

<?php

	// This page contains the connection routine for the
	// database as well as getting the ID of the cart, etc

	$dbServer = "localhost";
	$dbUser = "";
	$dbPass = "";
	$dbName = "cart";

	function ConnectToDb($server, $user, $pass, $database)
	{
		// Connect to the database and return
		// true/false depending on whether or
		// not a connection could be made.
		
		$s = @mysql_connect($server, $user, $pass);
		$d = @mysql_select_db($database, $s);
		
		if(!$s || !$d)
			return false;
		else
			return true;
	}
	
	function GetCartId()
	{
		// This function will generate an encrypted string and
		// will set it as a cookie using set_cookie. This will
		// also be used as the cookieId field in the cart table
		
		if(isset($_COOKIE["cartId"]))
		{
			return $_COOKIE["cartId"];
		}
		else
		{
			// There is no cookie set. We will set the cookie
			// and return the value of the users session ID
			
			session_start();
			setcookie("cartId", session_id(), time() + ((3600 * 24) * 30));
			return session_id();
		}
	}

?>

//products.php
<?php

	// This page will list all of the items
	// from the items table. Each item will have
	// a link to add it to the cart

	include("db.php");
	
	// Get a connection to the database
	$cxn = @ConnectToDb($dbServer, $dbUser, $dbPass, $dbName);
	$result = mysql_query("select * from items order by itemName asc");
	?>
		<html>
		<head>
		<title> Product List </title>
		</head>
		<body bgcolor="#ffffff">
		<h1>Products</h1>
		<table width="100%" cellspacing="0" cellpadding="0" border="0">
			<tr>
				<td width="30%" height="25" bgcolor="red">
					<font face="verdana" size="1" color="white">
						&nbsp;&nbsp;<b>Product</b>
					</font>
				</td>
				<td width="10%" height="25" bgcolor="red">
					<font face="verdana" size="1" color="white">
						<b>Price</b>
					</font>
				</td>
				<td width="50%" height="25" bgcolor="red">
					<font face="verdana" size="1" color="white">
						<b>Description</b>
					</font>
				</td>
				<td width="10%" height="25" bgcolor="red">
					<font face="verdana" size="1" color="white">
						<b>Add</b>
					</font>
				</td>
			</tr>
			<?php
			while($row = mysql_fetch_array($result))
			{
			?>
				<tr>
					<td width="30%" height="25">
						<font face="verdana" size="1" color="black">
							<?php echo $row["itemName"]; ?>
						</font>
					</td>
					<td width="10%" height="25">
						<font face="verdana" size="1" color="black">
							$<?php echo $row["itemPrice"]; ?>
						</font>
					</td>
					<td width="50%" height="25">
						<font face="verdana" size="1" color="black">
							<?php echo $row["itemDesc"]; ?>
						</font>
					</td>
					<td width="10%" height="25">
						<font face="verdana" size="1" color="black">
							<a href="cart.php?action=add_item&id=<?php echo $row["itemId"]; ?>&qty=1">Add Item</a>
						</font>
					</td>
				</tr>
				<tr>
					<td width="100%" colspan="4">
						<hr size="1" color="red" NOSHADE>
					</td>
				</tr>
			<?php
			}
		?>
			<tr>
				<td width="100%" colspan="4">
					<font face="verdana" size="1" color="black">
						<a href="cart.php">Your Shopping Cart >></a>
					</font>
				</td>
			</tr>
		</table>
	</body>
</html>

//cart.php
<?php

	include("db.php");
		
	switch($_GET["action"])
	{
		case "add_item":
		{
			AddItem($_GET["id"], $_GET["qty"]);
			ShowCart();
			break;
		}
		case "update_item":
		{
			UpdateItem($_GET["id"], $_GET["qty"]);
			ShowCart();
			break;
		}
		case "remove_item":
		{
			RemoveItem($_GET["id"]);
			ShowCart();
			break;
		}
		default:
		{
			ShowCart();
		}
	}

	function AddItem($itemId, $qty)
	{
		// Will check whether or not this item
		// already exists in the cart table.
		// If it does, the UpdateItem function
		// will be called instead
		
		global $dbServer, $dbUser, $dbPass, $dbName;

		// Get a connection to the database
		$cxn = @ConnectToDb($dbServer, $dbUser, $dbPass, $dbName);
		
[b]		// Check if this item already exists in the users cart table
		$result = mysql_query("select count(*) from cart where cookieId = '" . GetCartId() . "' and itemId = $itemId");
		$row = mysql_fetch_row($result);[/b]		$numRows = $row[0];
		
		if($numRows == 0)
		{
			// This item doesn't exist in the users cart,
			// we will add it with an insert query

			@mysql_query("insert into cart(cookieId, itemId, qty) values('" . GetCartId() . "', $itemId, $qty)");
		}
		else
		{
			// This item already exists in the users cart,
			// we will update it instead
			
			UpdateItem($itemId, $qty);
		}
	}
	
	function UpdateItem($itemId, $qty)
	{
		// Updates the quantity of an item in the users cart.
		// If the qutnaity is zero, then RemoveItem will be
		// called instead

		global $dbServer, $dbUser, $dbPass, $dbName;

		// Get a connection to the database
		$cxn = @ConnectToDb($dbServer, $dbUser, $dbPass, $dbName);
		
		if($qty == 0)
		{
			// Remove the item from the users cart
			RemoveItem($itemId);
		}
		else
		{
			mysql_query("update cart set qty = $qty where cookieId = '" . GetCartId() . "' and itemId = $itemId");
		}
	}
	
	function RemoveItem($itemId)
	{
		// Uses an SQL delete statement to remove an item from
		// the users cart

		global $dbServer, $dbUser, $dbPass, $dbName;

		// Get a connection to the database
		$cxn = @ConnectToDb($dbServer, $dbUser, $dbPass, $dbName);
		
		mysql_query("delete from cart where cookieId = '" . GetCartId() . "' and itemId = $itemId");
	}
	
	function ShowCart()
	{
		// Gets each item from the cart table and display them in
		// a tabulated format, as well as a final total for the cart
		
		global $dbServer, $dbUser, $dbPass, $dbName;

		// Get a connection to the database
		$cxn = @ConnectToDb($dbServer, $dbUser, $dbPass, $dbName);
		
		$totalCost = 0;
		$result = mysql_query("select * from cart inner join items on cart.itemId = items.itemId where cart.cookieId = '" . GetCartId() . "' order by items.itemName asc");
		?>
		<html>
		<head>
		<title> Your Shopping Cart </title>
		<script language="JavaScript">
		
			function UpdateQty(item)
			{
				itemId = item.name;
				newQty = item.options[item.selectedIndex].text;
				
				document.location.href = 'cart.php?action=update_item&id='+itemId+'&qty='+newQty;
			}
		
		</script>
		</head>
		<body bgcolor="#ffffff">
		<h1>Your Shopping Cart</h1>
		<form name="frmCart" method="get">
		<table width="100%" cellspacing="0" cellpadding="0" border="0">
			<tr>
				<td width="15%" height="25" bgcolor="red">
					<font face="verdana" size="1" color="white">
						&nbsp;&nbsp;<b>Qty</b>
					</font>
				</td>
				<td width="55%" height="25" bgcolor="red">
					<font face="verdana" size="1" color="white">
						<b>Product</b>
					</font>
				</td>
				<td width="20%" height="25" bgcolor="red">
					<font face="verdana" size="1" color="white">
						<b>Price Each</b>
					</font>
				</td>
				<td width="10%" height="25" bgcolor="red">
					<font face="verdana" size="1" color="white">
						<b>Remove?</b>
					</font>
				</td>
			</tr>
			[b]<?php
			
			while($row = mysql_fetch_array($result))
			{
				// Increment the total cost of all items
				$totalCost += ($row["qty"] * $row["itemPrice"]);
				?>[/b]
					<tr>
						<td width="15%" height="25">
							<font face="verdana" size="1" color="black">
								<select name="<?php echo $row["itemId"]; ?>" onChange="UpdateQty(this)">
								<?php
								
									for($i = 1; $i <= 20; $i++)
									{
										echo "<option ";
										if($row["qty"] == $i)
										{
											echo " SELECTED ";
										}
										echo ">" . $i . "</option>";
									}
								?>
								</select>
							</font>
						</td>
						<td width="55%" height="25">
							<font face="verdana" size="1" color="black">
								<?php echo $row["itemName"]; ?>
							</font>
						</td>
						<td width="20%" height="25">
							<font face="verdana" size="1" color="black">
								$<?php echo number_format($row["itemPrice"], 2, ".", ","); ?>
							</font>
						</td>
						<td width="10%" height="25">
							<font face="verdana" size="1" color="black">
								<a href="cart.php?action=remove_item&id=<?php echo $row["itemId"]; ?>">Remove</a>
							</font>
						</td>
					</tr>
				<?php
			}
			
			// Display the total
			?>
					<tr>
						<td width="100%" colspan="4">
							<hr size="1" color="red" NOSHADE>
						</td>
					</tr>
					<tr>
						<td width="70%" colspan="2">
							<font face="verdana" size="1" color="black">
								<a href="products.php"><< Keep Shopping</a>
							</font>
						</td>
						<td width="30%" colspan="2">
							<font face="verdana" size="2" color="black">
								<b>Total: $<?php echo number_format($totalCost, 2, ".", ","); ?></b>
							</font>
						</td>
					</tr>
				</table>
				</form>
			</body>
			</html>
			<?php
	}

?>
redmonkey
Forum Regular
Posts: 836
Joined: Thu Dec 18, 2003 3:58 pm

Post by redmonkey »

Difficult to tell as you are supressing almost all error messages. At a guess, I would say you are failing to establish a connection to the database.

Try unsupressing error messages or at least check that the database has returned something useful.
stantheman
Forum Commoner
Posts: 38
Joined: Wed May 26, 2004 8:57 am

Post by stantheman »

i'm connecting to the database becasue on the product page i get all the products it is when i click the add item button that it trows these two errors
redmonkey
Forum Regular
Posts: 836
Joined: Thu Dec 18, 2003 3:58 pm

Post by redmonkey »

Both functions AddItem and ShowCart attempt to make a seperate connection to the database.
stantheman
Forum Commoner
Posts: 38
Joined: Wed May 26, 2004 8:57 am

Post by stantheman »

I was able to get ride of the warning but it is now not adding anything to the cart
redmonkey
Forum Regular
Posts: 836
Joined: Thu Dec 18, 2003 3:58 pm

Post by redmonkey »

How did you get rid of the warning?
stantheman
Forum Commoner
Posts: 38
Joined: Wed May 26, 2004 8:57 am

Post by stantheman »

i was missing a database so i had to create it
redmonkey
Forum Regular
Posts: 836
Joined: Thu Dec 18, 2003 3:58 pm

Post by redmonkey »

As mentioned in my first post, try unsupressing error messages or at least check that the database has returned something useful.

I realise this is probably just a test environment, but, a shopping cart app with no error checking would just be asking for trouble.
stantheman
Forum Commoner
Posts: 38
Joined: Wed May 26, 2004 8:57 am

Post by stantheman »

i'm new to this php stuff so i'm not exactly sure how to go about it
EricS
Forum Contributor
Posts: 183
Joined: Thu Jul 11, 2002 12:02 am
Location: Atlanta, Ga

Post by EricS »

Take ALL of your error surpression off for now. Then run the script and see what errors occur. Post the errors here and we can help.

NOTE: When developing your applications, you should not surpress all the errors in the beginning, at least not until you become a very experienced PHP programmer. They are there to help you debug your applications quickly. You can put them back in later when your happy with the way the cart runs.

SECOND NOTE: Please use the BBCode to encapsulate your PHP code.
redmonkey
Forum Regular
Posts: 836
Joined: Thu Dec 18, 2003 3:58 pm

Post by redmonkey »

A couple of links to get you started..

http://www.zend.com/tips/tips.php?id=41&single=1
http://www.zend.com/tips/tips.php?id=114&single=1

These are very simple, techniques to get something semi-useful back from the database server if there is an error.
stantheman
Forum Commoner
Posts: 38
Joined: Wed May 26, 2004 8:57 am

Post by stantheman »

i've taken off my error surpression and it is not giving me anything when i'm on the products page and i click the additem link it goes to the cart.php page with nothing being desplayed.
redmonkey
Forum Regular
Posts: 836
Joined: Thu Dec 18, 2003 3:58 pm

Post by redmonkey »

Well, you will need to start going a bit deeper.

Some very basic debugging techniques are to stick in echos to show you the value of this.

I would start by checking that the correct values are getting into the database, e.g....

Code: Select all

$onething = 10;
$another = 10;
$result = mysql_query('SELECT something FROM somewhere WHERE $onething = $another');
echo $result;
This will display the SQL query and you can check that it is as supposed to be. You can use the same method for inserting data into the database.

Also check the value of display_errors and error_reporting within your php.ini file.
stantheman
Forum Commoner
Posts: 38
Joined: Wed May 26, 2004 8:57 am

Post by stantheman »

When i do my echo on the sql statemnt for adding it echos Resource id#3
redmonkey
Forum Regular
Posts: 836
Joined: Thu Dec 18, 2003 3:58 pm

Post by redmonkey »

It is quite clear I should be in bed asleep by now,LOL.

My snippet should have been more like.....

Code: Select all

$onething = 10;
$another = 10;
$sql = "SELECT something FROM somewhere WHERE $onething = $another";
$result = mysql_query($sql);
echo $sql;
Post Reply