Jump to content

Recommended Posts

This is my first post so please correct me if somethings wrong

Basically im creating a shopping cart with the help of a guide but there is no database written in the guide so i'm not sure how to proceed. My database wont work...
Guide:
https://jameshamilton.eu/programming/simple-php-shopping-cart-tutorial

Error message
http://gyazo.com/a2099d99b6606bb38b096b7727410dfd

Index:

  <?php session_start(); ?>
   <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
   <html xmlns="http://www.w3.org/1999/xhtml">
   <head>
   <meta name="description" content="PHP Shopping Cart Using Sessions" /> 
   <meta name="keywords" content="shopping cart tutorial, shopping cart, php, sessions" />
   <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
   <link rel="stylesheet" media="all" href="/style/style.css" type="text/css" />
   <title>Cart</title>
  
  
  <?php
  	//connect to your database here
  	
  
  $sql = 'SELECT * FROM books ORDER BY id';
  $output[] = '<ul>';
  $output[] = '<li>"'.$row['title'].'" by '.$row['author'].': £'.$row['price'].'<br /><a href="cart.php?action=add&id='.$row['id'].'">Add to cart</a></li>';
  
  
  //connect mysql
  
  mysql_connect($server, $user, $pass) or die ("Sorry, can't conect to mysql.");
  
  //select db
  
  mysql_select_db($db) or die ("Sorry cant select the db.");
  
  
  ?>
  
  
  
  </head>
  <body>
  
  
  <?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) {	
  				
  				//get the name, description and price from the database - this will depend on your database implementation.
  				//use sprintf to make sure that $product_id is inserted into the query as a number - to prevent SQL injection
  				$sql = sprintf("SELECT name, description, price FROM php_shop_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($name, $description, $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\">$name</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\">X</a></td>";
  						echo "<td align=\"center\">$line_cost</td>";
  					
 					echo "</tr>";
 					
 				}
 			
 			}
 			
 			//show the total
 			echo "<tr>";
 				echo "<td colspan=\"2\" align=\"right\">Total</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 "You have no items in your shopping 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 php_shop_products WHERE id = %d;",
 							$product_id); 
 				
 			return mysql_num_rows(mysql_query($sql)) > 0;
 	}
 ?>
 
 <a href="products.php">Continue Shopping</a>
 
 
 <?php
 
 /*
 
 products table:
 	CREATE TABLE `products` (
 		`id` INT NOT NULL AUTO_INCREMENT ,
 		`name` VARCHAR( 255 ) NOT NULL ,
 		`description` TEXT,
 		`price` DOUBLE DEFAULT '0.00' NOT NULL ,
 		PRIMARY KEY ( `id` )
 	);
 
 */
 
 ?>
 
 
 
 </body>
 </html>

products.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  <html xmlns="http://www.w3.org/1999/xhtml">
  <head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <meta name="description" content="PHP Shopping Cart Using Sessions" /> 
  <meta name="keywords" content="shopping cart tutorial, shopping cart, php, sessions" />
  <link rel="stylesheet" media="all" href="/style/style.css" type="text/css" />
  <title>Products</title>
  
 <?php
 	//connect to your database here
 		//connect to your database here
 	
 
 $sql = 'SELECT * FROM books ORDER BY id';
 $output[] = '<ul>';
 $output[] = '<li>"'.$row['title'].'" by '.$row['author'].': £'.$row['price'].'<br /><a href="cart.php?action=add&id='.$row['id'].'">Add to cart</a></li>';
 
 
 //connect mysql
 
 mysql_connect($server, $user, $pass) or die ("Sorry, can't conect to mysql.");
 
 //select db
 
 mysql_select_db($db) or die ("Sorry cant select the db.");
 ?>
 
 </head>
 
 <body>
 
 
 <table border="1">
 
 	<?php
 		
 		$sql = "SELECT id, name, description, price FROM php_shop_products;";
 		
 		$result = mysql_query($sql);
 		
 		while(list($id, $name, $description, $price) = mysql_fetch_row($result)) {
 		
 			echo "<tr>";
 			
 				echo "<td>$name</td>";
 				echo "<td>$description</td>";
 				echo "<td>$price</td>";
 				echo "<td><a href=\"cart.php?action=add&id=$id\">Add To Cart</a></td>";
 			
 			echo "</tr>";
 		}
 		
 	?>
 </table>
 
 
 <a href="cart.php">View Cart</a>
 
 </body>
 </html>
Link to comment
https://forums.phpfreaks.com/topic/289120-cant-connect-database-with-files/
Share on other sites

Am gonna stop you right there....that tutorial is 8 years old and using mysql_ functions.

 

Try to find one using mysqli_ or PDO instead.

 

Even a better suggestion is to use opencart, it's free and pretty good.

Edited by QuickOldCar

Is there no way to make this one work?

 

Um, yeah. But, why spend time trying to get an old, deprecated process to work when the process will likely be removed in the next release of PHP. I would guess most people are leaning towards PDO these days (I do). But, you can leverage what you have already written to use the mysqli_ extensions with very little effort.

 

As to your problem, saying "it doesn't work" provides us no information to work with. What errors are you getting? What is or is not being displayed? What have you tried to resolve the problems and what were the results?

Um, yeah. But, why spend time trying to get an old, deprecated process to work when the process will likely be removed in the next release of PHP. I would guess most people are leaning towards PDO these days (I do). But, you can leverage what you have already written to use the mysqli_ extensions with very little effort.

 

As to your problem, saying "it doesn't work" provides us no information to work with. What errors are you getting? What is or is not being displayed? What have you tried to resolve the problems and what were the results?

It just says undefined variables.. nothing is displayed and i haven't been able to figure out a solution.

Edited by Danielmm

It just says undefined variables.. nothing is desplayed and i haven't been able to figure out a solution.

 

OK, that error is just what it means. You are trying to 'use' a variable that has not been defined. But, you don't state for "which" variables you are getting that error. I know you may not have a lot of experience, but providing the actual errors you are receiving would seem like an obvious thing to include.

 

So, with the undefined error. These are likely warning/notice errors (I forget which one). These can be suppressed (and should be in a production environment). But, you want these errors on in a development environment because it helps to prevent hard to find defects. For example, If you define a variable $data and later try to reference that variable using $Data. Here are a couple places that I could see you getting that error

 

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

 

If you were to access the page and didn't include variables on the query string for 'id' and 'action' then you are referencing values that don't exist. If the errors were suppressed and $_GET[id] does not exist, then $product_id would be defined as a NULL value and, if your page was coded appropriately, everything would work just fine. But, as I stated above you want to have these errors enabled in development so you can ensure the code is of high quality.

 

What I typically use in this situation is the ternary operator (a shorthand if/else) to test if the GET value is defined and set the variable accordingly

 

    $product_id = isset($_GET['id']) ? $_GET['id'] : false;     //the product id from the URL 
    $action     = isset($_GET['action']) ? $_GET['action'] : false; //the action from the URL

NOTE: Textual array indexes should be enclosed in quote as in my example above.

 

So, I don't see how the errors you say you are getting have anything to do with your database. If you want further help, please provide details.

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.