Jump to content
Larry Ullman's Book Forums

Recommended Posts

In the example in the book, quantity, total and product_id are stored in the cart session. I am trying to add product_name, but I am not sure how to assign this to the session. I have added product_name to the array and put the value of $pn (not sure if this is correct!!) But would like to know what I do next and how I add this to the SESSION['cart']

 

When I view the session array product_name is not shown:

Array ( [318] => Array ( [quantity] => 4 [price] => 6.00 [product_name] => ) )

 

  <?php 
print_r($_SESSION['cart']);
$page_title = 'Add to cart';
if (isset ($_GET['pid']) && is_numeric($_GET['pid']) ) {
$pid = (int) $_GET['pid'];
if (isset($_SESSION['cart'][$pid])) {
	$_SESSION['cart'][$pid]['quantity']++;
}else{ //new product
require_once ('../mysqli_connect.php');
$q="SELECT price FROM product WHERE product_id=$pid";
$r=mysqli_query ($dbc, $q);
if (mysqli_num_rows($r) == 1) {
list($price) = mysqli_fetch_array ($r, MYSQLI_NUM);
$_SESSION['cart'][$pid] = array ('quantity' => 1, 'price' => $price, 'product_name' => $pn);
}else{
echo '<div align="center">Your basket has been updated</div>';
}
}
}else{ //no print ID
echo '<div align="center"> Your basket has been updated</div>';
}
# Script 17.9 - view_cart.php. 
if (isset($_POST['submitted'])) {
foreach ($_POST['qty'] as $k => $v) {

	$pid = (int) $k;
	$qty = (int) $v;

	if ($qty ==0) { // Delete.
		unset ($_SESSION['cart'][$pid]);
	} elseif ($qty >0 ) { // Change quantity.
		$_SESSION['cart'][$pid]['quantity'] = $qty;
	}

} // End of FOREACH.
} // End of SUBMITTED IF.
if (!empty($_SESSION['cart'])) {
require_once ('../mysqli_connect.php'); 
$q="SELECT product_id, description, price, product_name FROM product WHERE product_id IN (";													   
foreach ($_SESSION['cart'] as $pid => $value) {
	$q .= $pid . ',';
}
$q=substr($q, 0, -1) . ') ORDER BY product_name ASC';
$r = mysqli_query ($dbc, $q);

echo '<form action="basket.php" method="post">
<table border="0" width="90%" cellspacing="3" cellpadding="3" align="center">
<tr>
	<td align="left" width="30%"><b>Description</b></td>
	<td align="left" width="30%"><b>Product Name</b></td>
	<td align="right" width="10%"><b>Price</b></td>
	<td align="center" width="10%"><b>Qty</b></td>
	<td align="right" width="10%"><b>Total Price</b></td>
</tr>
';

$total =0; // Total cost of the order.
while ($row = mysqli_fetch_array ($r, MYSQLI_ASSOC)) {

	$subtotal = $_SESSION['cart'][$row['product_id']]['quantity'] * $_SESSION['cart'][$row['product_id']]['price'];
	$postage=1.99;
	$total += ($postage + $subtotal);

// Print the row.
	echo "\t<tr>
	<td align=\"left\">{$row['description']}</td>
	<td align=\"left\">{$row['product_name']}</td>
	<td align=\"right\">£{$_SESSION['cart'][$row['product_id']]['price']}</td>
	<td align=\"center\"><input type=\"text\" size=\"3\" name=\"qty[{$row['product_id']}]\" value=\"{$_SESSION['cart'][$row['product_id']]['quantity']}\" /></td>
	<td align=\"right\">£" . number_format ($subtotal, 2) . "</td>
</tr>\n";

} // End of the WHILE loop.
mysqli_close($dbc); // Close the database connection.
echo '<tr>

	<td colspan="4" align="right"><b> Postage:</b></td><br/>
	<td align="right">£' . number_format ($postage, 2) . '</td>
	<br/>
	<br/>
	<br/>
	<br/>
	<td colspan="4" align="right"><b>Total:</b></td>
	<td align="right">£' . number_format ($total, 2) . '</td>
</tr>
</table><p align="left">Enter a quantity of 0 to remove an item.
<div align="left"><input type="submit" name="submit" value="Update" /></div>
<input type="hidden" name="submitted" value="TRUE" />
<p align="center"><a href="../logincustomer.php"><img src="checkout.gif" width="83" height="27" border="0" /></a></p>';

} else {
echo '<p>Your cart is currently empty.</p>';
}
?>

Link to comment
Share on other sites

Your $pn variable has no value. You'll need to change your query so that it selects the product name as well as the price (e.g., SELECT price, product_name FROM...). Then you change the list() function call to

list($price, $pn) = mysqli_fetch_array...

Link to comment
Share on other sites

Your $pn variable has no value. You'll need to change your query so that it selects the product name as well as the price (e.g., SELECT price, product_name FROM...). Then you change the list() function call to

list($price, $pn) = mysqli_fetch_array...

 

This works great, but now I have a problem on the next page (user login) where it does not recognise the product_name or $pn. It recognises price and customer_id. What do I need to add to this page so that it shows the product_name? Thanks.

 

          <?php # Script 16.8 - login.php
session_start();
require_once ('admin/config.inc.php'); 
$page_title = 'Login';
$email_subject='Order';
$email_message='test';
$headers='Thank you for your order;
$email_from='info@xxx.co.uk';
if (isset($_POST['submitted'])) {
require_once (MYSQL);
$trimmed = array_map('trim', $_POST);
if (preg_match ('/^[\w.-]+@[\w.-]+\.[A-Za-z]{2,6}$/', $trimmed['email'])) {
	$e = mysqli_real_escape_string ($dbc, $trimmed['email']);
} else {
			$e = FALSE;
	echo '<p class="error">Please enter a valid email address!</p>';
}
if (!empty($_POST['password'])) {
	$p = mysqli_real_escape_string ($dbc, $_POST['password']);
} else {
	$p = FALSE;
	echo '<p class="error">You forgot to enter your password!</p>';
}
if ($e && $p) { // If everything's OK.
	// Query the database:
	$q = "SELECT customer_id, firstname FROM customers WHERE (email='$e' AND password=SHA1('$p') )";		
	$r = mysqli_query ($dbc, $q) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($dbc));
	if (@mysqli_num_rows($r) == 1) { // A match was made.

	$row = mysqli_fetch_array ($r, MYSQLI_ASSOC);
	$_SESSION['customer_id'] = $row['customer_id'];
$me = $_SESSION['customer_id'];
$t = $_SESSION['total'];
$pn = $_SESSION['product_name'];
$body = "Thank you for your order. Your customer ID is '$me',You have ordered '$pn'\nPlease quote your customer number if you need to contact us.\n\n The total cost of your order is '$t'";
			ini_set("sendmail_from", "info@xxx.co.uk");
			mail($trimmed['email'], $email_subject, $body, $headers, '-f'.$email_from);
			mail($cc, $email_subject, $body, $headers, '-f'.$email_from);

		$url = BASE_URL . 'checkout2.php'; // Define the URL:
		ob_end_clean(); // Delete the buffer.
		header("Location: $url/");
		exit(); // Quit the script.

	} else { // No match was made.
		echo '<p class="error">Either the email address and password entered do not match those on file or you have not yet activated your account.</p>';
	}

} else { // If everything wasn't OK.
	echo '<p class="error">Please try again.</p>';
}

//mysqli_close($dbc);

} // End of SUBMIT conditional.
?>

Link to comment
Share on other sites

You need to assign the value into the session - you're trying to do this:

 

$pn = $_SESSION['product_name'];

 

But no value is ever assigned into this session variable... you need a line like this below in the script that originally defines $pn.

 

$_SESSION['product_name'] = $pn;

Link to comment
Share on other sites

You need to assign the value into the session - you're trying to do this:

 

$pn = $_SESSION['product_name'];

 

But no value is ever assigned into this session variable... you need a line like this below in the script that originally defines $pn.

 

$_SESSION['product_name'] = $pn;

 

I tried that, but get:

An error has occured 'Undefined variable: pn

Link to comment
Share on other sites

How about posting the updated code so we can help?

 

It is the code as above:

    <?php # Script 16.8 - login.php 
session_start(); 
require_once ('admin/config.inc.php');  
$page_title = 'Login'; 
$email_subject='Order'; 
$email_message='test'; 
$headers='Thank you for your order; 
$email_from='info@xxx.co.uk'; 
if (isset($_POST['submitted'])) { 
       require_once (MYSQL); 
       $trimmed = array_map('trim', $_POST); 
       if (preg_match ('/^[\w.-]+@[\w.-]+\.[A-Za-z]{2,6}$/', $trimmed['email'])) { 
               $e = mysqli_real_escape_string ($dbc, $trimmed['email']); 
       } else { 
                               $e = FALSE; 
               echo '<p class="error">Please enter a valid email address!</p>'; 
       } 
       if (!empty($_POST['password'])) { 
               $p = mysqli_real_escape_string ($dbc, $_POST['password']); 
       } else { 
               $p = FALSE; 
               echo '<p class="error">You forgot to enter your password!</p>'; 
       } 
       if ($e && $p) { // If everything's OK. 
               // Query the database: 
               $q = "SELECT customer_id, firstname FROM customers WHERE (email='$e' AND password=SHA1('$p') )";                 
               $r = mysqli_query ($dbc, $q) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($dbc)); 
               if (@mysqli_num_rows($r) == 1) { // A match was made. 

               $row = mysqli_fetch_array ($r, MYSQLI_ASSOC); 
               $_SESSION['customer_id'] = $row['customer_id']; 
$me = $_SESSION['customer_id']; 
$t = $_SESSION['total']; 
$_SESSION['product_name'] = $pn;


$body = "Thank you for your order. Your customer ID is '$me',You have ordered '$pn'\nPlease quote your customer number if you need to contact us.\n\n The total cost of your order is '$t'"; 
                               ini_set("sendmail_from", "info@xxx.co.uk"); 
                               mail($trimmed['email'], $email_subject, $body, $headers, '-f'.$email_from); 
                               mail($cc, $email_subject, $body, $headers, '-f'.$email_from); 

                       $url = BASE_URL . 'checkout2.php'; // Define the URL: 
                       ob_end_clean(); // Delete the buffer. 
                       header("Location: $url/"); 
                       exit(); // Quit the script. 

               } else { // No match was made. 
                       echo '<p class="error">Either the email address and password entered do not match those on file or you have not yet activated your account.</p>'; 
               } 

       } else { // If everything wasn't OK. 
               echo '<p class="error">Please try again.</p>'; 
       } 

       //mysqli_close($dbc); 

} // End of SUBMIT conditional. 
?>

The error message is:

An error has occured 'Undefined variable: pn

Link to comment
Share on other sites

Okay, I don't exactly know how to help you here. You've posted no code wherein a product name is stored in $_SESSION['product_name']. In this last bit of code, you're assigning the value of $pn to $_SESSION['product_name'], which doesn't make any sense if you think about it. First of all, $pn has no value in this script. Second, $_SESSION['product_name'] should have previously been assigned and should be retrieved at this point, as the other session values are (I believe that's what you're trying to do). This is what Stuart was trying to say earlier, too.

 

Also keep in mind that a very basic debugging technique is to do a print_r($_SESSION) to show what values are stored in the session.

Link to comment
Share on other sites

In my basket.php I have as part of my $_SESSION['cart'];

$q="SELECT price, product_name FROM product WHERE product_id=$pid";
$r=mysqli_query ($dbc, $q);
if (mysqli_num_rows($r) == 1) {
list($price, $pn) = mysqli_fetch_array ($r, MYSQLI_NUM);
$_SESSION['cart'][$pid] = array ('quantity' => 1, 'price' => $price, 'product_name' => $pn);

 

When I go to the next page logincustomer.php it brings accross price and product_id as you outlined in your book, but not the product_name that I have added to the code. $pn that I am assigning to this next page is what I had in my basket.php file.

 

I am wanting to bring the values from basket.php to the next page as it does with $price.

Link to comment
Share on other sites

That's helpful to see. As you can tell from your own code, there is no $_SESSION['product_name'] being created. You're creating $_SESSION['cart'][$pid]['product_name']. This is just the same as you have with the price.

Link to comment
Share on other sites

That's helpful to see. As you can tell from your own code, there is no $_SESSION['product_name'] being created. You're creating $_SESSION['cart'][$pid]['product_name']. This is just the same as you have with the price.

 

Thanks for the reply. I am creating as shown in the book, the examples you use in the book (ie, price and quantity) show, but I get the error message when I try to create a new addition in the $_SESSION['cart'];

 

An error has occured 'Undefined variable: pn

[row] => Array

(

[customer_id] => 5

[firstname] => kerry

)

 

[me] => 5

[t] => 4.49

[pn] =>

 

Basket:

if (mysqli_num_rows($r) == 1) {
list($price, $pn) = mysqli_fetch_array ($r, MYSQLI_NUM);
$_SESSION['cart'][$pid] = array ('quantity' => 1, 'price' => $price, 'product_name' => $pn);

 

Loginpage:

$me = $_SESSION['customer_id'];
$t = $_SESSION['total'];
$pn = $_SESSION['cart'][$pid]['product_name'];
$body = "Thank you for your order. Your customer ID is '$pn','$me', \nPlease quote your customer number if you need to contact us.\n\n The total cost of your order is '$t'";

 

What do I need to add to the basket or loginpage to get the product_name or $pn to bring accross the value?

Link to comment
Share on other sites

It works fine in the basket.php page and the $pn is shown.

if (mysqli_num_rows($r) == 1) { 
       list($price, $pn) = mysqli_fetch_array ($r, MYSQLI_NUM); 
       $_SESSION['cart'][$pid] = array ('quantity' => 1, 'price' => $price, 'product_name' => $pn);

 

In the logincustomer.php page. I get the 'Undefined variable: pn

$me = $_SESSION['customer_id']; 
$t = $_SESSION['total']; 
$pn = $_SESSION['cart'][$pid]['product_name']; 
$body = "Thank you for your order. Your customer ID is '$pn','$me', \nPlease quote your customer number if you need to contact us.\n\n The total cost 

 

No, the $pid is not in the loginpage:

		// Query the database:
	$q = "SELECT customer_id, firstname FROM customers WHERE (email='$e' AND password=SHA1('$p') )";		
	$r = mysqli_query ($dbc, $q) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($dbc));
	if (@mysqli_num_rows($r) == 1) { // A match was made.

	$row = mysqli_fetch_array ($r, MYSQLI_ASSOC);
	$_SESSION['customer_id'] = $row['customer_id'];

$me = $_SESSION['customer_id'];
$t = $_SESSION['total'];

 

$pid is as the example in your book where you have $aid, but instead of artist id I have product id. Should this be in the loginpage and where?

Link to comment
Share on other sites

It works fine in the basket.php page and the $pn is shown.

 

I'm not sure what you mean by "shown".

 

In the logincustomer.php page. I get the 'Undefined variable: pn

 

The code you've posted, which creates a $pn variable, would not cause that error. It'd probably help to see the full error.

 

 

No, the $pid is not in the loginpage:

 

Okay. If $pid is not in the loginpage (is that the same as the logincustomer.php page?), then you can refer to $_SESSION['cart'][$pid]['product_name'].

 

$pid is as the example in your book where you have $aid, but instead of artist id I have product id. Should this be in the loginpage and where?

 

 

I think you're confused here. In the book, $aid is an artist's ID and $pid is a product ID. $pid represents a specific item being purchased. I don't know why a $pid would be involved with a login page, but it's really not clear what you're doing here.

 

 

Link to comment
Share on other sites

 Share

×
×
  • Create New...