PHP shopping basket

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

Post Reply
someone2088
Forum Commoner
Posts: 42
Joined: Thu Nov 17, 2011 1:09 pm

PHP shopping basket

Post by someone2088 »

Hi,

I am trying to create a shopping basket using PHP, but can't seem to work out how to add items to the basket.

Currently, I have a table which contains a list of games, along with a price and description for each game. The table also has a column which contains a checkbox for every entry. What I want to do is that when a user checks one or more checkboxes, they should be able to click an 'add to basket' button, which would add the items whose checkbox they have ticked to the shopping basket. I then need to be able to display the contents of the shopping basket (i.e. all the games whose checkbox was ticked) on another page.

This is the code for the page containing the list of games:

Code: Select all

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<?php 
session_start(); 
	// retrieve stored session data (this line doesn't display the session variable-
	// it only retrieves it, ready to be used elsewhere in the page).
	$_SESSION['userName']=$_POST['userName'];
?>


<html>
<head>
<title>Home</title><a href="logout.php">Log Out</a>
</head>
<body>
<h1>Home</h1>

<?php
	// retrieve session data- userName (this line displays the session variable- as it
	// has already been retrieved at the top of the file.
	echo "Welcome ".$_SESSION['userName']."!"; 
	
	// display how many items the user currently has in their shopping basket
	function writeShoppingBasket(){
		$basket = $_SESSION['basket'];
		if(!$basket){
			return '<p>You have no items in your shopping basket</p>';
		}else{
			$items = explode(',',$basket);
			$s = (count($items) > 1) ? 's':'';
			return '<p>You have <a href="shoppingBasket.php">'.count($items).' item'.$s.' in your shopping basket.</a></p>';
		}
	}	
	
?>

<p>
<a href="shoppingBasket.php">View your shopping basket</a>
<br /></p>

<?php
	echo extension_loaded('pgsql');
	
	$conn_string = "host=***** port=**** dbname=***** user=***** password=*****";
	$dbconn = pg_connect($conn_string);
	
	if(!$dbconn){
		die('Could not connect: ' . pg_error());
		}
		
	// generate and execute a simple query to check that the php script is connecting
	// to the database, and that SQL queries will return required data. 
	$query = "SELECT * FROM CSGames";
	$result = pg_query($dbconn, $query) or die("Error in query: $query." . pg_last_error($dbconn));
	// Get the number of games in the resultset
	$rows = pg_num_rows($result);
	echo "\n There are currently $rows games in the database.";
?>
<p><br /></p>	

<h1>Search for games by price: </h1>

<p>Enter price range of games you would like to search for:</p>

<form action="gamesByPrice.php" method="post">

Miniumum price: <input type="text" name="minPrice" />
Maximum price: <input type="text" name="maxPrice" />
<input type="submit" value="Search" />
</form>

<?php
	// This stores the values that the user entered for min and max price, so that
	// a user can search for games by any particular price range.
	$_SESSION ['minPrice']="minPrice";
	$_SESSION ['maxPrice']="maxPrice";	
?>
 

<?php
	
	// query to retrieve titles of all games from database, with their price and description
	$gameTitlesQuery = "SELECT title, price, description FROM CSGames";
	$gameTitlesQueryResult = pg_query($dbconn, $gameTitlesQuery) or die("Error in query: $gameTitlesQuery." . pg_last_error($dbconn));
	?>

	
<?php
	// print out the data stored in the $gameTitleQueryResult variable in a table
	echo '<div id="Games">';
	echo '<table id="Games" border="1">';
	while ($a=pg_fetch_row($gameTitlesQueryResult)){
		echo '<tr>';
		for ($i=0; $i<pg_num_fields($gameTitlesQueryResult); $i++){
			echo '<td>'.htmlspecialchars($a[$i], ENT_QUOTES).'</ td>';
		}
	echo "<td><input type='checkbox' name='selectGame' value='{$a['refnumber']}' /></ td>
	</ tr>";
	}
	echo '</table></ div>';
?>


</body>
</html>
If someone could point me in the right direction, I'd be very grateful.
User avatar
social_experiment
DevNet Master
Posts: 2793
Joined: Sun Feb 15, 2009 11:08 am
Location: .za

Re: PHP shopping basket

Post by social_experiment »

I would make the 'selectGame' an array;

Code: Select all

<input type="checkbox" name="selectGame[]" value="aValue" />
When the user submits their choice you check pass the items in $_POST['selectGame'] to the $_SESSION['basket'] variable

Code: Select all

<?php
    // button clicked
    if (is_array($_POST['selectGame'])) {
        if (count($_POST['selectGame']) > 0) {
             foreach ($_POST['selectGame'] as $chosenItem) {
                 $_SESSION['basket'][] = $chosenItem;
             } 
         }
     }
?>
Hth
“Don’t worry if it doesn’t work right. If everything did, you’d be out of a job.” - Mosher’s Law of Software Engineering
someone2088
Forum Commoner
Posts: 42
Joined: Thu Nov 17, 2011 1:09 pm

Re: PHP shopping basket

Post by someone2088 »

Thanks for your reply, but I can't seem to get it working the way that you have suggested. Another thought I'd had was to maybe try and use JavaScript to keep track of which checkboxes had been checked, and then just add the titles associated with those checkboxes to the shopping cart- but I'm not too sure how you would do this. Any suggestions?
User avatar
social_experiment
DevNet Master
Posts: 2793
Joined: Sun Feb 15, 2009 11:08 am
Location: .za

Re: PHP shopping basket

Post by social_experiment »

Code: Select all

<?php
	session_start();
?>
<html>
<head>
<title>This is a test</title>
</head>
<body>
<form action="" method="post" >

1. <input type="checkbox" value="1" name="checkBox[]" />
2. <input type="checkbox" value="2" name="checkBox[]" />
3. <input type="checkbox" value="3" name="checkBox[]" />
<br />
<input type="submit" value="Add to basket" name="button" />
</form>
<?php
 if (isset($_POST['button'])) {
	//print_r($_POST);
	if (is_array($_POST['checkBox'])) {
		foreach ($_POST['checkBox'] as $chosenItem) {
			$_SESSION['basket'][] = $chosenItem;
		}
	}
 }
 
 
 
 
?>
<pre>
<?php
	if (isset($_SESSION['basket'])) {
		print_r($_SESSION['basket']);
	}
	/*
	Array
(
    [0] => 2
    [1] => 1
    [2] => 2
    [3] => 3
)


	*/
?>
</pre>
</body>
</html>
This is a simplified version of what i'm trying to explain; can you paste the code you created
“Don’t worry if it doesn’t work right. If everything did, you’d be out of a job.” - Mosher’s Law of Software Engineering
Post Reply