Hello All,
I am fairly new to PHP ... I am trying to build a basic order form for a small wholesale database and am completely stuck.

The function of this page is display items and their price from the database along with an input box that will allow the user to enter an an order amount for each item. View The Page When the form is submitted I need to be able to multiply the Items price by the amount entered in the input box to get an item total. These totals will then be added together to get the Grand total.

The problem I have is twofold.
The Price Variable $ItemPrice is retrieved from the database using the command:

while($row=mysqli_fetch_array($result)){
         echo '$ ' . $row['ItemPrice'] . ' 
}

As far as I can tell this only makes the Value of $ItemPrice available while the loop is being performed so when I run my "submit" script I cannot call the price with $ItemPrice.

// Check for Submission
    if (isset($_POST['submit'])) {
    // Grab the quantity  from the POST
	$ItemOrder = mysqli_real_escape_string($dbc, trim($_POST['ItemOrder']));
	//Calculate and display the Item Total
	$Price=$ItemPrice;
	$LineTotal = $Price*$ItemOrder;
	echo '<p class="info">The Line Total is: $' . $LineTotal . '</p>';
	}

The Second Problem:
Since the items and prices in the order form are created dynamically I need to be able to create a unique set of variables for each item so instead of just referring to $ItemPrice I need to be able to preform the function of the submit button on all the items in the list based on each items price and the amount entered in the form. So that $ItemPrice1 would be multiplied by $ItemOrder1 and stored in $LineTotal1 and so forth so that I could then total all the $LineTotalx values and get a $GrandTotal

Here is the PHP Code

<?php
  // Start the session
  require_once('startsession.php');

  // Insert the page header
  $page_title = 'Place A New Order';
  require_once('header.php');

  require_once('appvars.php');
  require_once('connectvars.php');

  // Show the navigation menu
  require_once('navmenu.php');



  // Connect to the database 
  $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME); 

  // Check for Submission
    if (isset($_POST['submit'])) {
    // Grab the quantity  from the POST
	$ItemOrder = mysqli_real_escape_string($dbc, trim($_POST['ItemOrder']));
	//Calculate and display the Item Total
	$Price=$ItemPrice;
	$LineTotal = $Price*$ItemOrder;
	echo '<p class="info">The Line Total is: $' . $LineTotal . '</p>';
	}
	else {
        // No Amount Entered
        echo '<p class="error">Please Enter Amount</p>';
        $LineTotal = "0";
      }
    
 
  // Retrieve the product data from MySQL
  $query="SELECT * FROM `items` ORDER BY 'ItemCat' ";
  $result = mysqli_query($dbc, $query);
  
  


  // Loop through the array of product data, formatting it as HTML 
  echo '<div id="form_box">';
  echo ' <h1>Upper Crust Wholesale - Online Order</h1>
  <p class="error">Please Complete the form below to place your order.</p><hr>';
  ?>
  <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
  <?php
  
   while($row=mysqli_fetch_array($result)) 
   {  
	    // Display the product data
	 echo '<div class="product_line">';
	echo '<div class="prod_name">' . $row['ItemName'] . ' / ' .$row['ItemCat'] . '</div>';
	echo '<div class="prod_price">$ ' . $row['ItemPrice'] . ' ... per ... ' . $row['ItemAmount'] . ' ' . $row['ItemUnit'] . '' ; 
	?>
    <label for="ItemOrder">Quantity:</label>
      <input type="text" size="5" name="ItemOrder" value="<?php if (!empty($ItemOrder)) echo $ItemOrder; ?>" />
      
      </div></div>
<?php	
'</div>';
  }
?>
 <br />
 <input type="submit" value="Update Total" name="submit" />
 </form>
<?php

  mysqli_close($dbc);


  // Insert the page footer
  require_once('footer.php');
?>

Thanks for looking I am open to any advice on making this approach work or even alternative ways of coding this type of page.

This should work as long as you have an id field in the item table (which you should):

<?php

$page_title = 'Place A New Order';

require_once('startsession.php');
require_once('header.php');
require_once('appvars.php');
require_once('connectvars.php');
require_once('navmenu.php');

$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME); 

$items = array();

$query = mysqli_query( $dbc,"SELECT `ItemID`,`ItemName`,`ItemCat`,`ItemPrice`,`ItemAmount`,`ItemUnit` FROM `items` ORDER BY `ItemCat` ASC" );
while( list( $id,$name,$cat,$price,$amount,$unit ) = mysqli_fetch_array( $query ) ) {
	$items[$id] = array(
		'name'   => $name,
		'cat'    => $cat,
		'price'  => $price,
		'amount' => $amount,
		'unit'   => $unit
	);
}

if ( isset( $_POST['submit'] ) ) {
	$total = 0;
	foreach( $_POST as $key => $value ) {
		$value = (int) $value;
		if ( isset( $items[$key] ) ) {
			$item =& $items[$key];
			$item['quanity'] = $value;
			$total += ( $item['price'] * $value );
		}
	}
	echo "<p class=\"info\">The Line Total is: \${$total}</p>";
}
else {
	echo '<p class="error">Please Enter Amount</p>';
}

echo <<<HTML
<div id="form_box">
	<h1>Upper Crust Wholesale - Online Order</h1>
	<p class="error">Please complete the form below to place your order.</p><hr />
	<form action="{$_SERVER['PHP_SELF']}" method="post">
HTML;
foreach( $items as $id => $item ) {
	if ( !isset( $item['quanity'] ) ) {
		$item['quanity'] = 0;
	}
	echo <<<HTML
		<div class="product_line">
			<div class="prod_name">{$item['name']} / {$item['cat']}</div>
			<div class="prod_price">\$ {$item['price']} ... per ... {$item['amount']} {$item['unit']}
				<label for="{$id}">Quanity:</label>
				<input type="text" name="{$id}" size="5" value="{$item['quanity']}" />
			</div>
		</div>

HTML;
}
echo <<<HTML
		<br />
		<input type="submit" name="submit" value="Update Total" />
	</form>
HTML; 

mysqli_close( $dbc );

require_once('footer.php');

?>

Its untested so there will probably be errors. Let me know what they are and I will tell you how to fix them.

Keith,
Thanks for the quick and through reply ... This all looks very promising ... I have inserted your code and uploaded it to my server, but am getting the following error:
Parse error: syntax error, unexpected $end ... /order_page.php on line 73

I googled the error and looks like this error is often caused by an unbalanced tag or quote, but I dont see any ... I did add a comma after the the last array item
'unit' => $unit
changed to
'unit' => $unit,
but that did not fix this error.

Thanks Again

Everything looks like its ok. It must be something in your includes.

I am using the same template that I have for the sample page I also have these includes on half a dozen other pages with no errors?...
Just in case I have removed the includes and replaced them with the code here so you can have a look.
This code is posted to: http://cubicalstudio.com/wholesale/order_page.php
Thanks Again,

<!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" xml:lang="en" lang="en">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<?php
  echo '<title>The Upper Crust / Wholesale  - ' . $page_title . '</title>';
?>

  <link rel="stylesheet" type="text/css" href="wholesale_overall.css" />
</head>
<body>
<div id="container">
<?php
  echo '<h1>The Upper Crust / Wholesale  - ' . $page_title . '</h1>';

require_once('connectvars.php');


$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME); 

$items = array();

$query = mysqli_query( $dbc,"SELECT `ItemID`,`ItemName`,`ItemCat`,`ItemPrice`,`ItemAmount`,`ItemUnit` FROM `items` ORDER BY `ItemCat` ASC" );
while( list( $id,$name,$cat,$price,$amount,$unit ) = mysqli_fetch_array( $query ) ) {
	$items[$id] = array(
		'name'   => $name,
		'cat'    => $cat,
		'price'  => $price,
		'amount' => $amount,
		'unit'   => $unit
	);
}

if ( isset( $_POST['submit'] ) ) {
	$total = 0;
	foreach( $_POST as $key => $value ) {
		$value = (int) $value;
		if ( isset( $items[$key] ) ) {
			$item =& $items[$key];
			$item['quanity'] = $value;
			$total += ( $item['price'] * $value );
		}
	}
	echo "<p class=\"info\">The Line Total is: \${$total}</p>";
}
else {
	echo '<p class="error">Please Enter Amount</p>';
}

echo <<<HTML
<div id="form_box">
	<h1>Upper Crust Wholesale - Online Order</h1>
	<p class="error">Please complete the form below to place your order.</p><hr />
	<form action="{$_SERVER['PHP_SELF']}" method="post">
HTML;
foreach( $items as $id => $item ) {
	if ( !isset( $item['quanity'] ) ) {
		$item['quanity'] = 0;
	}
	echo <<<HTML
		<div class="product_line">
			<div class="prod_name">{$item['name']} / {$item['cat']}</div>
			<div class="prod_price">\$ {$item['price']} ... per ... {$item['amount']} {$item['unit']}
				<label for="{$id}">Quanity:</label>
				<input type="text" name="{$id}" size="5" value="{$item['quanity']}" />
			</div>
		</div>

HTML;
}
echo <<<HTML
		<br />
		<input type="submit" name="submit" value="Update Total" />
	</form>
HTML; 

mysqli_close( $dbc );
?>

  </div> <!--End of container-->
</body>
</html>

Remove all of the includes and just run the code I created by itself. Slowly start removing sections to see which one is causing the problem.

It seems that the problem was with the last bit of code in your post I am not familiar with the way you change from php to html so I just closed the php tag and re-entered the end of the form in straight html.

echo <<<HTML
		<br />
		<input type="submit" name="submit" value="Update Total" />
	</form>
HTML;

Changed to:

?>
   <br />
		<input class="submit" type="submit" name="submit" value="Update Total" />
        
	</form>
   
<?php

You can view the working page here:
http://cubicalstudio.com/wholesale/order_page.php

The only problem I am having is that when you update an amount in any of the fields The last entry in the list becomes a duplicate of the one above it ... The odd thing is that the $ItemPrice value is still correct for that row but the displayed product info is not ...
Any Ideas
Thanks,

This is an example on how to display the individual totals.

<?php

$page_title = 'Place A New Order';

require_once('startsession.php');
require_once('header.php');
require_once('appvars.php');
require_once('connectvars.php');
require_once('navmenu.php');

$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME); 

$items = array();

$query = mysqli_query( $dbc,"SELECT `ItemID`,`ItemName`,`ItemCat`,`ItemPrice`,`ItemAmount`,`ItemUnit` FROM `items` ORDER BY `ItemCat` ASC" );
while( list( $id,$name,$cat,$price,$amount,$unit ) = mysqli_fetch_array( $query ) ) {
	$items[$id] = array(
		'name'   => $name,
		'cat'    => $cat,
		'price'  => $price,
		'amount' => $amount,
		'unit'   => $unit
	);
}

if ( isset( $_POST['submit'] ) ) {
	$total = 0;
	foreach( $_POST as $key => $value ) {
		list( ,$key ) = explode( '-',$key );
		$value = (int) $value;
		if ( isset( $items[$key] ) ) {
			$item =& $items[$key];
			$item['quanity'] = $value;
			$price = ( $item['price'] * $value );
			echo "{$item['name']} - {$item['price']} x {$item['quanity']} = {$price}<br />";
			$total += $price;
		}
	}
	echo "<p class=\"info\">The Line Total is: \${$total}</p>";
}
else {
	echo '<p class="error">Please Enter Amount</p>';
}

echo <<<HTML
<div id="form_box">
	<h1>Upper Crust Wholesale - Online Order</h1>
	<p class="error">Please complete the form below to place your order.</p><hr />
	<form action="{$_SERVER['PHP_SELF']}" method="post">
HTML;
foreach( $items as $id => $item ) {
	if ( !isset( $item['quanity'] ) ) {
		$item['quanity'] = 0;
	}
	echo <<<HTML
		<div class="product_line">
			<div class="prod_name">{$item['name']} / {$item['cat']}</div>
			<div class="prod_price">\$ {$item['price']} ... per ... {$item['amount']} {$item['unit']}
				<label for="item-{$id}">Quanity:</label>
				<input type="text" name="item-{$id}" size="5" value="{$item['quanity']}" />
			</div>
		</div>

HTML;
}



?>
		<br />
		<input type="submit" name="submit" value="Update Total" />
	</form> 
<?php

mysqli_close( $dbc );

require_once('footer.php');

?>

As for the duplicate problem, just clear the database and reenter the information. Give the script a clean start.

Keith,
I have been trying to get this script to work without doubling the last line after you submit the form. I have deleted and re added the table but that did not have any affect ...

The best I can tell is that it has to do with this part of the script running again after the form is submitted.

HTML;
foreach( $items as $id => $item ) {
	if ( !isset( $item['quantity'] ) ) {
		$item['quantity'] = 0;
	}
	echo <<<HTML
		<div class="product_line">
			<div class="prod_name">{$item['name']} / {$item['cat']}</div>
			<div class="prod_price">\${$item['price']} ... per ... {$item['amount']} {$item['unit']}
				<label for="item-{$id}">Quantity:</label>
				<input type="text" name="item-{$id}" size="5" value="{$item['quantity']}" />
			</div>
		</div>

HTML;
}

The process I want to do calls for the submit script to be run multiple times ... the first time would be to see what your order totals would be and the second time would be to submit the order to the database.

However after the script runs the first time the last item and its order amount are overwritten by the preceeding item. If you then say submit order ... the order is placed for the correct item (because the item ID is still correct if you look at the html) but the order amounts are not correct because they have been overwritten by the preceeding items values.

Here is what my current code looks like:
View the current page here:
http://cubicalstudio.com/wholesale/order_page_no_login.php

<?php

$page_title = 'Place A New Order';

require_once('startsession.php');
require_once('header.php');
require_once('appvars.php');
require_once('connectvars.php');
require_once('navmenu.php');

  // Make sure the user is logged in before going any further.
  if (!isset($_SESSION['VisitorID'])) {
    echo '<p class="login">Please <a href="login.php">log in</a> to access this page.</p>';
    exit();
  }

$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME); 

$items = array();

$query = mysqli_query( $dbc,"SELECT `ItemID`,`ItemName`,`ItemCat`,`ItemPrice`,`ItemAmount`,`ItemUnit` FROM `items` ORDER BY `ItemCat` ASC" );
while( list( $id,$name,$cat,$price,$amount,$unit ) = mysqli_fetch_array( $query ) ) {
	$items[$id] = array(
		'name'   => $name,
		'cat'    => $cat,
		'price'  => $price,
		'amount' => $amount,
		'unit'   => $unit,
		'id'     => $id
	);
}
	echo '<div id="form_box">';
	echo '<div id ="totalbox">';
if ( isset( $_POST['update'] ) ) {
    
	$total = 0;
	foreach( $_POST as $key => $value ) {
		list( ,$key ) = explode( '-',$key );
		$value = (int) $value;
		if ( isset( $items[$key] ) ) {
			$item =& $items[$key];
			$item['quantity'] = $value;
			$price = ( $item['price'] * $value );
			$tax_rate = 0.035;
			$item_tax = ($price * $tax_rate);
			$item_tax = number_format($item_tax, 2);
			if ($value != 0){
			echo "{$item['name']} / {$item['cat']} - \${$item['price']} x {$item['quantity']} = \${$price}<br />";
			}
			$total += $price;
			$tax += $item_tax;
			$grand_total = $tax + $total;
		}
	}
	echo "<p class=\"orderinfo\">Sub Total: \${$total}</p>";
	echo "<p class=\"orderinfo\">Tax: \${$tax}</p>";
	echo "<p class=\"orderinfo\">Grand Total: \${$grand_total}</p>";
	echo '<p>NOTE: Your order has not yet been submitted ... Please click the SUBMIT ORDER button to complete the order process.</p>';
	
	
	//show order form again
echo <<<HTML
	<form name="orderform" action="{$_SERVER['PHP_SELF']}" method="post">
	<input type="submit" name="order" value="Submit Order" />
	<hr>
	<br /><br />
HTML;
foreach( $items as $id => $item ) {
	if ( !isset( $item['quantity'] ) ) {
		$item['quantity'] = 0;
	}
	echo <<<HTML
		<div class="product_line">
			<div class="prod_name">{$item['name']} / {$item['cat']}</div>
			<div class="prod_price">\${$item['price']} ... per ... {$item['amount']} {$item['unit']}
				<label for="item-{$id}">Quantity:</label>
				<input type="text" name="item-{$id}" size="5" value="{$item['quantity']}" />
			</div>
		</div>

HTML;
}



?>

<br />
<input type="submit" name="update" value="Update Total" />

</form>
</div>
<?php

mysqli_close( $dbc );

require_once('footer.php');


	
	exit();
}


if ( isset( $_POST['order'] ) ) {
    
	//create initial order ID
	
	$create_order = "INSERT INTO orders (OrderVisitorID, OrderDate) VALUES ('$_SESSION[VisitorID]', NOW())";
	mysqli_query($dbc, $create_order);
	// store new order ID as a variable
	
	$query = 'SELECT * FROM orders ORDER BY OrderID DESC LIMIT 1'; 
    $result = mysqli_query($dbc, $query);
	 while ($row = mysqli_fetch_array($result)) { 
    $OrderID = $row["OrderID"];
	}
	//reset total value to 0
	$total = 0;
	//process form data
	foreach( $_POST as $key => $value ) {
		list( ,$key ) = explode( '-',$key );
		$value = (int) $value;
		if ( isset( $items[$key] )) {
			$item =& $items[$key];
			$item['quantity'] = $value;
			$price = ( $item['price'] * $value );
			//calculate tax
			$tax_rate = 0.035;
			$item_tax = ($price * $tax_rate);
			$item_tax = number_format($item_tax, 2);
			//display order details
			if ($value != 0 ){
			echo "{$item['name']} / {$item['cat']} - \${$item['price']} x {$item['quantity']} = \${$price}<br />";
			//save order details to orderdetails table
			$insert = "INSERT INTO orderdetails (DetailItemID, DetailItemName, DetailItemCat, DetailOrderID, DetailQuantity, DetailPrice, DetailTotal, DetailTaxTotal)  VALUES ('$item[id]', '$item[name]', '$item[cat]', '$OrderID', $value, $item[price], '$price', '$item_tax')";
				 mysqli_query($dbc, $insert);
			}
			
            //display order totals
			$total += $price;
			$tax += $item_tax;
			$grand_total = $tax + $total;
			//$grand_total=$Delete;
					
			
		   //save order totals in orders table
		  
	
		   $update_total = "UPDATE orders SET OrderSubTotal=$total, OrderTax=$tax, OrderTotal=$grand_total WHERE OrderID=$OrderID ";
	    mysqli_query($dbc, $update_total);
		}
		//Delete Empty Orders 
			//if ('Delete' == 0) {
			//$sql ='DELETE FROM orders WHERE OrderID=$OrderID LIMIT 1;';
			//$delete_order = mysqli_query($dbc, $sql);
			//echo "Please enter an amount to place an order.";
		// }
		
	}
	echo "<p class=\"orderinfo\">Sub Total: \${$total}</p>";
	echo "<p class=\"orderinfo\">Tax: \${$tax}</p>";
	echo "<p class=\"orderinfo\">Grand Total: \${$grand_total}</p>";
	echo "<p class=\"orderinfo\">Thank You - Your Order Has Been Submitted.  </p>";
	
	exit();
}


echo <<<HTML
	<form name="orderform" action="{$_SERVER['PHP_SELF']}" method="post">
HTML;
foreach( $items as $id => $item ) {
	if ( !isset( $item['quantity'] ) ) {
		$item['quantity'] = 0;
	}
	if ( $cat != z){
	echo <<<HTML
		<div class="product_line">
			<div class="prod_name">{$item['name']} / {$item['cat']}</div>
			<div class="prod_price">\${$item['price']} ... per ... {$item['amount']} {$item['unit']}
				<label for="item-{$id}">Quantity:</label>
				<input type="text" name="item-{$id}" size="5" value="{$item['quantity']}" />
			</div>
		</div>

HTML;
}

}

?>

<br />
<input type="submit" name="update" value="Update Total" />

</form>
</div>
<?php

mysqli_close( $dbc );

require_once('footer.php');

?>

Thanks for all your help.

Eric

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.