SitePoint Sponsor

User Tag List

Results 1 to 9 of 9
  1. #1
    SitePoint Zealot blackberryfan's Avatar
    Join Date
    Nov 2010
    Location
    middleOnowhere, South Africa.
    Posts
    101
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    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:

    Code:
    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:

    Code:
    <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:

    Code:
    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:

    Code:
    $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!!

  2. #2
    SitePoint Wizard bronze trophy chris.upjohn's Avatar
    Join Date
    Apr 2010
    Location
    Melbourne, AU
    Posts
    2,191
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    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.

  3. #3
    SitePoint Zealot blackberryfan's Avatar
    Join Date
    Nov 2010
    Location
    middleOnowhere, South Africa.
    Posts
    101
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by SgtLegend View Post
    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.
    Code:
    $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 .= '
    		<tr>
    			<td>'.$prId.'</td>
    	    	<td>'.$prDesc.'</td>
    			<td>'.$prPack.'x'.$prSize.' '.$prMeasure.'</td>
    			<td>R'.$prPrice1.'</td>
    			<td>
    				<form action="" method="post">
    					<div>
    						<input type="text" size="3" name="quantity" /> 
    					</div>
    				</form>
    			</td>
    			<td>
    				<form action="" method="post">
    					<div>
    						<input type="hidden" name="id" value="'.$prId.'" />
    						<input type="submit" name="action" value="Order" />
    					</div>
    				</form>
    			</td>			
    	   </tr>
    ';
    }}
    What I am having trouble with is adding each selected row to the session.

    Which in essence would be this little bit right here:

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

  4. #4
    From space with love silver trophy
    SpacePhoenix's Avatar
    Join Date
    May 2007
    Location
    Poole, UK
    Posts
    5,027
    Mentioned
    103 Post(s)
    Tagged
    0 Thread(s)
    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.
    Community Team Advisor
    Forum Guidelines: Posting FAQ Signatures FAQ Self Promotion FAQ
    Help the Mods: What's Fluff? Report Fluff/Spam to a Moderator

  5. #5
    SitePoint Zealot blackberryfan's Avatar
    Join Date
    Nov 2010
    Location
    middleOnowhere, South Africa.
    Posts
    101
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by SpacePhoenix View Post
    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?

  6. #6
    SitePoint Zealot blackberryfan's Avatar
    Join Date
    Nov 2010
    Location
    middleOnowhere, South Africa.
    Posts
    101
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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.

  7. #7
    Non-Member bronze trophy
    Join Date
    Nov 2009
    Location
    Keene, NH
    Posts
    3,760
    Mentioned
    23 Post(s)
    Tagged
    0 Thread(s)
    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...

    Code:
    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.

  8. #8
    SitePoint Zealot blackberryfan's Avatar
    Join Date
    Nov 2010
    Location
    middleOnowhere, South Africa.
    Posts
    101
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by deathshadow60 View Post
    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...

    Code:
    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

    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:

    Code:
    $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 .= '
    		<tr>
    			<td>'.$prId.'</td>
    	    	<td>'.$prDesc.'</td>
    			<td>'.$prPack.'x'.$prSize.' '.$prMeasure.'</td>
    			<td>R'.$prPrice1.'</td>
    			<td>
    				<form action="" method="post">
    					<div>
    						<input type="hidden" name="id" value="'.$prId.'" />
    						<input type="submit" name="action" value="Order" />
    					</div>
    				</form>
    			</td>			
    	   </tr>
    ';
    
    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';
    
    ?>
    Here is the orders-layout include:

    Code:
    <?php
    ob_start();
    
    $belowMenu = '
    	<p>Orders Page</p>
    ';
    
    $pageContent = '
        <h2>Place your order</h2>
        <p>Your order contains '.count($_SESSION['order']).' items.</p>
    	<p><a href="?order">View your order</a></p>
    	<table border="1">
    		<thead>
    			<tr>
    				<th>Stock Code</th>
    				<th>Description</th>
    				<th>Packsize</th>
    				<th>Price</th>
    				<th>Quantity</th>
    			</tr>
    		</thead>
    		<tbody>
    ';
    
    	$pageContentEnd = '
    		</tbody>
    	</table>
    	<br />
    	<p>All prices are inclusive of VAT</p>
    ';
    
    
    echo $head1 . $pageDetails . $head2 . $header . $menu . $belowMenu . $content . $pageContent . $orderContent . $pageContentEnd . $footer . $pageScripts;
    exit;
    ?>
    Here is the orders-finalize include:

    Code:
    <?php
    ob_start();
    
    $belowMenu = '
    	<p>Orders Page</p>
    ';
    
    $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) 
    	{
    		if ($item == $prId) 
    		{
    			$pageContent .= '
    					<tr>
    						<td>'.$prDesc.'</td>
    						<td>
    							R'.number_format($prPrice1, 2).'
    						</td>
    					</tr>
    ';		
    		}
    	}
    		$pageContent .= '
    			</tbody>
    			</table>
    ';
    		
    } else
    { 
    	$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="Clear order" />
    		</p>
    	</form>
    ';
    
    
    echo $head1 . $pageDetails . $head2 . $header . $menu . $belowMenu . $content . $pageContent . $footer . $pageScripts;
    exit;
    ?>
    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!

  9. #9
    SitePoint Zealot blackberryfan's Avatar
    Join Date
    Nov 2010
    Location
    middleOnowhere, South Africa.
    Posts
    101
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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?


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •