PHP/MYSQL - while($row = mysql_fetch_assoc($result)) - How to select an entire row?

I am working on a simple order system, based on the sitepoint book “Build your own Database Driven Web Site Using PHP & MYSQL” By Kevin Yank.

the peice of code I am stuck on is the following:

if (isset($_GET['cart']))
{
$cart = array();
$total = 0;
foreach ($_SESSION['cart'] as $id)
{
    foreach ($items as $product)
    {
        if ($product['id'] == $id)
        {
            $cart[] = $product;
            $total += $product['price'];
            break;
        }
    }
}

include 'cart.html.php';
exit();
}

To display this cart, the following script is used:

<body>
		<h1>Your Shopping Cart</h1>
		<?php if (count($cart) > 0): ?>
		<table>
			<thead>
				<tr>
					<th>Item Description</th>
					<th>Price</th>
				</tr>
			</thead>
			<tfoot>
				<tr>
					<td>Total:</td>
					<td>$<?php echo number_format($total, 2); ?></td>
				</tr>
			</tfoot>
			<tbody>
				<?php foreach ($cart as $item): ?>
					<tr>
						<td><?php htmlout($item['desc']); ?></td>
						<td>
							$<?php echo number_format($item['price'], 2); ?>
						</td>
					</tr>
				<?php endforeach; ?>
			</tbody>
		</table>
		<?php else: ?>
		<p>Your cart is empty!</p>
		<?php endif; ?>
		<form action="?" method="post">
			<p>
				<a href="?">Continue shopping</a> or
				<input type="submit" name="action" value="Empty cart"/>
			</p>
		</form>
	</body>

This is the code is build on a preset array. I am working with a table with a few columns in mysql.

I have am trying to adapt it so that the content is drawn out of a Mysql table. I have the following so far:

if (isset($_GET['order']))
{
	$orders = array();
	$total = 0;
	foreach ($_SESSION['order'] as $id)
	{
		while($row = mysql_fetch_assoc($productsSql)) {
			foreach ($prId as $product)
			{
			if ($row == $id) {
				$orders[] = $product;
				$total += $prPrice1;
				break;
				}
			}
		}

	include($docRoot . '/orders-finalize.php');
	exit();
	}
}

To display this cart I have adapated the script like this:

$pageContent = '
    <h2>Your order</h2>
';
	if (count($order) > 0) {
		$pageContent .= '
		<table>
			<thead>
				<tr>
					<th>Item Description</th>
					<th>Price</th>
				</tr>
			</thead>
			<tfoot>
				<tr>
					<td>Total:</td>
					<td>R'.number_format($total, 2).'</td>
				</tr>
			</tfoot>
			<tbody>
';
		foreach ($order as $item) {
			$pageContent .= '
					<tr>
						<td>'.$item['desc'].'</td>
						<td>
							R'.number_format($item['price1'], 2).'
						</td>
					</tr>
';
		
		}
$pageContent .= '
		</tbody>
		</table>
		';
		if (count($order) == 0) { 
		$pageContent .= '
		<p>Your cart is empty!</p>
		';
		}
		
	}
		$pageContent .= '
		<form action="?" method="post">
			<p>
				<a href="?">Continue shopping</a> or
				<input type="submit" name="action" value="Empty cart"/>
			</p>
		</form>
';


echo $head1 . $pageDetails . $head2 . $header . $menu . $belowMenu . $content . $pageContent . $footer . $pageScripts;
exit;

All this seems to do is produce my cart in a fashion where when viewed it displays a list of only the items’ id, e.g. where the description and price are supposed to be, I only get the items id in both fields… I also get a total price of 0.

Can anyone spot where I am going wrong here?

Or atleast try to give me some input so that I get going in the right direction!

Thanks!!

In your above code you don’t have a MySQL query anywhere, you have a reference to $productsSql but there is no query within your actual foreach loop.

$productsQuery = 'SELECT `id`, `refCode`, `desc`, `pack`, `measure`, `quantity`, `deptCode`, `taxable`, `price1`, `price2`, `crdCode`, `cost1`, `cost2` FROM `products` ORDER BY `desc` ';
$productsSql = mysql_query($productsQuery) or die(mysql_error());
if (mysql_num_rows($productsSql) == 0) {
	die('No results.');
} else {
	$orderContent = '';
    while($row = mysql_fetch_assoc($productsSql)) {
	$prId = $row['id'];
	$prRefCode = $row['refCode'];
	$prDesc = $row['desc'];
	$prPack = $row['pack'];
	$prMeasure = $row['measure'];
	$prQuantity = $row['quantity'];
	$prDeptCode = $row['deptCode'];
	$prTaxable = $row['taxable'];
	$prPrice1 = $row['price1'];
	$prPrice2 = $row['price2'];
	$prCrdCode = $row['crdCode'];
	$prCost1 = $row['cost1'];
	$prCost2 = $row['cost2'];
	$orderContent .= '
		&lt;tr&gt;
			&lt;td&gt;'.$prId.'&lt;/td&gt;
	    	&lt;td&gt;'.$prDesc.'&lt;/td&gt;
			&lt;td&gt;'.$prPack.'x'.$prSize.' '.$prMeasure.'&lt;/td&gt;
			&lt;td&gt;R'.$prPrice1.'&lt;/td&gt;
			&lt;td&gt;
				&lt;form action="" method="post"&gt;
					&lt;div&gt;
						&lt;input type="text" size="3" name="quantity" /&gt; 
					&lt;/div&gt;
				&lt;/form&gt;
			&lt;/td&gt;
			&lt;td&gt;
				&lt;form action="" method="post"&gt;
					&lt;div&gt;
						&lt;input type="hidden" name="id" value="'.$prId.'" /&gt;
						&lt;input type="submit" name="action" value="Order" /&gt;
					&lt;/div&gt;
				&lt;/form&gt;
			&lt;/td&gt;			
	   &lt;/tr&gt;
';
}}

What I am having trouble with is adding each selected row to the session.

Which in essence would be this little bit right here:

foreach ($items as $product)
    {
        if ($product['id'] == $id)
        {
            $cart[] = $product;
            $total += $product['price'];
            break;
        }
    }

Is there a field called size? It’s not mentioned in the SELECT clause but the value is used in the form.

The use of ` is not needed if a field name doesn’t use a reserved words. Assuming that the MySQL server is version 5.1 then here is a list of reserved words for that version.

Hi there,

Thank you for the input! The size field is not defined as of yet, this is because I am lacking the data to insert into that column at this moment in time. It is only there as a place holder to remind me that I need this data.

As for not needing the `, well that I did not know. I am very new to this and this would be one of the first applications that I am designing myself using php and mysql.

I guess I need to read up more on the use of sessions before I will come right here. I have a page that displays all the rows in the table “products”. When I click on order, it adds 1 to the session, although I am not sure what information has been added the session. When i click on view order, for some reason it resets the session count and refreshes the current page.

I am busy reading a book called Effortless E-commerce by Larry Ullman, It has provided me with some insight on the matter, but his use of the cart application is not quite what I am trying to accomplish.

Does anyone have any links to php based cart tutorials using mysql?

I think that i see what the real problem here is now.

When a user clicks order, it adds the id of the specific row to the session.

On the cart page, the script checks the values of the session against the id values of each row stored in the table, if the values match, the corresponding row in the table is returned. For each session value, this process is repeated until all its values are displayed. If there are no values in the session, then a value of “cart is empty” is displayed.

I understood it originally as when a user clicks order, all the values in that specific row are stored in the session, then displayed on the cart page as some kind of array.

Quite different indeed.

My big question would be why are you wasting time copying all those values into local variables, when you’re just throwing them away?

Also, little tip, if you REALLY don’t want that as an array…


while (
	list(
		$prId,
		$prRefCodem,
		$prDesc,
		$prPack,
		$prMeasure,
		$prQuantity,
		$prDeptCode,
		$prTaxable,
		$prPrice1,
		$prPrice2,
		$prCrdCode,
		$prCost1,
		$prCost2
	) = mysql_fetch_assoc($productsSql) 
) {

Though seriously, just use the array directly… either way, don’t waste ram and processing time making two copies of the same values for no good reason.

I’m also curious how you expect your first separate form to work with no submit, or even why it’s a separate form… NOT that multi-row forms are simple.

I have plans for those variables in the future, where as certain users will have access to certain information, or certain variations of it :slight_smile:

I will take your tip, but what does that while list actually do? assign values to each column?

Well that form was part of the original brain storm. You see I am a very big noob. And well, what I was trying to do with that was create a way for a user to order more than one of a specific item.

At the moment thought, I am working on a functional script, where a user can add an item to the “cart”, then view its contents.

This is the first part with the preceeding info removed:

$productsQuery = 'SELECT `id`, `refCode`, `desc`, `pack`, `measure`, `quantity`, `deptCode`, `taxable`, `price1`, `price2`, `crdCode`, `cost1`, `cost2` FROM `products` ORDER BY `desc` ';
$productsSql = mysql_query($productsQuery) or die(mysql_error());

session_start();
if (!isset($_SESSION['order']))
{
	$_SESSION['order'] = array();
}

if (isset($_POST['action']) and $_POST['action'] == 'Order')
{
	// Add item to the end of the $_SESSION['order'] array
	$_SESSION['order'][] = $_POST['id'];
	header('Location: .');
	exit();
}

if (isset($_POST['action']) and $_POST['action'] == 'Clear order')
{
	// Empty the $_SESSION['order'] array
	unset($_SESSION['order']);
	header('Location: ?order');
	exit();
}

if (mysql_num_rows($productsSql) == 0)
{
	die('No results.');
} else
{
	$orderContent = '';
    while($row = mysql_fetch_assoc($productsSql))
 {
	$prId = $row['id'];
	$prRefCode = $row['refCode'];
	$prDesc = $row['desc'];
	$prPack = $row['pack'];
	$prMeasure = $row['measure'];
	$prQuantity = $row['quantity'];
	$prDeptCode = $row['deptCode'];
	$prTaxable = $row['taxable'];
	$prPrice1 = $row['price1'];
	$prPrice2 = $row['price2'];
	$prCrdCode = $row['crdCode'];
	$prCost1 = $row['cost1'];
	$prCost2 = $row['cost2'];
	$orderContent .= '
		&lt;tr&gt;
			&lt;td&gt;'.$prId.'&lt;/td&gt;
	    	&lt;td&gt;'.$prDesc.'&lt;/td&gt;
			&lt;td&gt;'.$prPack.'x'.$prSize.' '.$prMeasure.'&lt;/td&gt;
			&lt;td&gt;R'.$prPrice1.'&lt;/td&gt;
			&lt;td&gt;
				&lt;form action="" method="post"&gt;
					&lt;div&gt;
						&lt;input type="hidden" name="id" value="'.$prId.'" /&gt;
						&lt;input type="submit" name="action" value="Order" /&gt;
					&lt;/div&gt;
				&lt;/form&gt;
			&lt;/td&gt;			
	   &lt;/tr&gt;
';

if (isset($_GET['order']))
{
	$order = array();
	$total = 0;
	foreach ($_SESSION['order'] as $id)
	{
			foreach ($prId as $product)
			{
			if ($product == $id) 
				{
				$order[] = $product;
				$total += $prPrice1;
				break;
				}
			}

	include($docRoot . '/orders/orders-finalize.php');
	exit();
		
	}
}
}}
include 'orders-layout.php';

?&gt;

Here is the orders-layout include:

&lt;?php
ob_start();

$belowMenu = '
	&lt;p&gt;Orders Page&lt;/p&gt;
';

$pageContent = '
    &lt;h2&gt;Place your order&lt;/h2&gt;
    &lt;p&gt;Your order contains '.count($_SESSION['order']).' items.&lt;/p&gt;
	&lt;p&gt;&lt;a href="?order"&gt;View your order&lt;/a&gt;&lt;/p&gt;
	&lt;table border="1"&gt;
		&lt;thead&gt;
			&lt;tr&gt;
				&lt;th&gt;Stock Code&lt;/th&gt;
				&lt;th&gt;Description&lt;/th&gt;
				&lt;th&gt;Packsize&lt;/th&gt;
				&lt;th&gt;Price&lt;/th&gt;
				&lt;th&gt;Quantity&lt;/th&gt;
			&lt;/tr&gt;
		&lt;/thead&gt;
		&lt;tbody&gt;
';

	$pageContentEnd = '
		&lt;/tbody&gt;
	&lt;/table&gt;
	&lt;br /&gt;
	&lt;p&gt;All prices are inclusive of VAT&lt;/p&gt;
';


echo $head1 . $pageDetails . $head2 . $header . $menu . $belowMenu . $content . $pageContent . $orderContent . $pageContentEnd . $footer . $pageScripts;
exit;
?&gt;

Here is the orders-finalize include:

&lt;?php
ob_start();

$belowMenu = '
	&lt;p&gt;Orders Page&lt;/p&gt;
';

$pageContent = '
    &lt;h2&gt;Your order&lt;/h2&gt;
';
	if (count($order) &gt; 0)
{
		$pageContent .= '
		&lt;table&gt;
			&lt;thead&gt;
				&lt;tr&gt;
					&lt;th&gt;Item Description&lt;/th&gt;
					&lt;th&gt;Price&lt;/th&gt;
				&lt;/tr&gt;
			&lt;/thead&gt;
			&lt;tfoot&gt;
				&lt;tr&gt;
					&lt;td&gt;Total:&lt;/td&gt;
					&lt;td&gt;R'.number_format($total, 2).'&lt;/td&gt;
				&lt;/tr&gt;
			&lt;/tfoot&gt;
			&lt;tbody&gt;
';	
		foreach ($order as $item) 
	{
		if ($item == $prId) 
		{
			$pageContent .= '
					&lt;tr&gt;
						&lt;td&gt;'.$prDesc.'&lt;/td&gt;
						&lt;td&gt;
							R'.number_format($prPrice1, 2).'
						&lt;/td&gt;
					&lt;/tr&gt;
';		
		}
	}
		$pageContent .= '
			&lt;/tbody&gt;
			&lt;/table&gt;
';
		
} else
{ 
	$pageContent .= '
	&lt;p&gt;Your cart is empty!&lt;/p&gt;
';
}
		
	$pageContent .= '
	&lt;form action="?" method="post"&gt;
		&lt;p&gt;
			&lt;a href="?"&gt;Continue shopping&lt;/a&gt;
			or
			&lt;input type="submit" name="action" value="Clear order" /&gt;
		&lt;/p&gt;
	&lt;/form&gt;
';


echo $head1 . $pageDetails . $head2 . $header . $menu . $belowMenu . $content . $pageContent . $footer . $pageScripts;
exit;
?&gt;

This produces a page where each result is listed.

If the user clicks “view order”, It should lead to a page where the user can see all the items that have been ordered.

What it actually does, is empty the session and refresh the page.

If anyone can spot where I am going wrong here, It would be appreciated if you could pass on some input!

By taking the include “orders-finalize” out of the foreach loop, it allows me to view orders-finalize. By my problem now is that the array $order is not getting carried over to this page. All that is displayed is “your cart is empty”

Can anyone spot where I am going wrong with this?