php echo in html table - php

I'm quite new to html and php, I've tried a few things trying to achieve what i want but it never works.
It's a shopping cart, I'm trying to display data from mysql using php in a table, it would be simple if I didn't have other elements that I want to display in the table as well ($value and $sub) which aren't stored in mysql but are calculations.
When I don't try to display it in a table it all works perfectly, and when I add the table I can only get the 'name' to display in the table, If I try to include anything else it fails.
Code below displays 'name' under the table name column, next thing to display would be '$value' under quantity and so on (haven't added anymore columns yet)
foreach($_SESSION as $name => $value) {
if ($value>0) {
if (substr($name, 0, 5)=='cart_') {
$id = substr($name, 5, (strlen($name)-5));
$get = mysql_query('SELECT id_product, name, price FROM elec_guit WHERE id_product='.($id));
while ($get_row = mysql_fetch_assoc($get)) {
$sub = $get_row['price']*$value;
?>
<div class="table">
<table>
<tr>
<td>Name</td>
<td>Quantity</td>
</tr>
<tr>
<?php echo '<td>' .$get_row['name']. '</td>' .$value. ' # &dollar;'.number_format($get_row['price'], 2). ' = &dollar;'.number_format($sub, 2).' [-] [+] <a href="cart.php?delete='.$id.'" >[Delete]</a><br />';
}
}
$total += $sub;
}
}
?>
</tr>
</table>

Possible code to render column and row properly.
<div class="table">
<table>
<tr>
<td>Name</td>
<td>Quantity</td>
</tr>
foreach($_SESSION as $name => $value) {
if ($value>0) {
if (substr($name, 0, 5)=='cart_') {
$id = substr($name, 5, (strlen($name)-5));
$get = mysql_query('SELECT id_product, name, price FROM elec_guit WHERE id_product='.($id));
while ($get_row = mysql_fetch_assoc($get)) {
$sub = $get_row['price']*$value;
?>
<tr>
<?php echo '<td>' .$get_row['name']. '</td>' .$value. ' # &dollar;'.number_format($get_row['price'], 2). ' = &dollar;'.number_format($sub, 2).' [-] [+] <a href="cart.php?delete='.$id.'" >[Delete]</a><br />';
}
}
$total += $sub;
}
}
?>
</tr>
</table>
Thanks
Amit

First thing i want to tell you is mysql_* is officially deprecated as of PHP 5.5. And removed entirely as of PHP 7.0. So please dont use it.
Refer : http://php.net/manual/en/migration55.deprecated.php
For mysqli_* : http://php.net/manual/en/book.mysqli.php
Now about you code :
You are using table tag inside the loop. This will generate multiple tables. Try out this code :
<div class="table">
<table>
<tr>
<td>Name</td>
<td>Quantity</td>
</tr>
<?php
foreach($_SESSION as $name => $value) {
if ($value>0) {
if (substr($name, 0, 5)=='cart_') {
$id = substr($name, 5, (strlen($name)-5));
$get = mysql_query("SELECT id_product, name, price FROM elec_guit WHERE id_product='$id'");
while ($get_row = mysql_fetch_assoc($get)) {
$sub = $get_row['price']*$value;
echo '<tr><td>' . $get_row['name']. '</td>' .
'<td>' . $value. ' # &dollar;'.number_format($get_row['price'], 2).
' = &dollar;'.number_format($sub, 2).' [-] [+]'
'<a href="cart.php?delete='.$id.'" >[Delete]</a></td></tr>';
}
}
$total += $sub;
}
}
?>
</table>

Added new code as per your comment.
<div class="table">
<table>
<tr>
<td>Name</td>
<td>Quantity</td>
</tr>
foreach($_SESSION as $name => $value) {
if ($value>0) {
if (substr($name, 0, 5)=='cart_') {
$id = substr($name, 5, (strlen($name)-5));
$get = mysql_query('SELECT id_product, name, price FROM elec_guit WHERE id_product='.($id));
while ($get_row = mysql_fetch_assoc($get)) {
$sub = $get_row['price']*$value;
?>
<tr>
<?php echo '<td>' .$get_row['name']. $value. ' # &dollar;'.number_format($get_row['price'], 2). ' = &dollar;'.number_format($sub, 2).' [-] [+] <a href="cart.php?delete='.$id.'" >[Delete]</a><br /></td> </tr>';
}
}
$total += $sub;
}
}
?>
</table>

I moved the table outside of your loop, that will fix a majority of your problems. Another issue is you only had one <td> wrapping the name column in your while loop, but you didn't have a <td> wrapping the other information in that row, so I wrapped that.
<div class="table">
<table>
<tr>
<td>Name</td>
<td>Quantity</td>
</tr>
<?php
foreach($_SESSION as $name => $value) {
if ($value>0) {
if (substr($name, 0, 5)=='cart_') {
$id = substr($name, 5, (strlen($name)-5));
$get = mysql_query('SELECT id_product, name, price FROM elec_guit WHERE id_product='.($id));
while ($get_row = mysql_fetch_assoc($get)) {
$sub = $get_row['price']*$value;
echo '<tr><td>' . $get_row['name']. '</td>' .
'<td>' . $value. ' # &dollar;'.number_format($get_row['price'], 2).
' = &dollar;'.number_format($sub, 2).' [-] [+]'
'<a href="cart.php?delete='.$id.'" >[Delete]</a></td></tr>';
}
}
}
}
?>
</table>
</div>

Use the below code:
<div class="table">
<table>
<tr>
<td>Name</td>
<td>Quantity</td>
</tr>
<?php
foreach($_SESSION as $name => $value) {
if ($value>0) {
if (substr($name, 0, 5)=='cart_') {
$id = substr($name, 5, (strlen($name)-5));
$get = mysql_query('SELECT id_product, name, price FROM elec_guit WHERE id_product='.($id));
while ($get_row = mysql_fetch_assoc($get)) {
$sub = $get_row['price']*$value;
?>
<tr>
<td><?php echo $get_row['name']; ?></td>
<td><?php echo $value;?> # &dollar;<?php echo number_format($get_row['price'], 2); ?> = &dollar;<?php echo number_format($sub, 2); ?> [-] [+] <a href="cart.php?delete=<?php echo $id; ?>" >[Delete]</a><br /></td>
</tr>
<?php }
}
$total += $sub;
}
}
?>
</table>
</div>

Related

php / MySQL - How to join 'cart' table together

How can I join this table together, showing the header only once? I have tried to take th out of the while loop but I had no luck, maybe I made a mistake?
Here is my code so far:
<?php
function cart() {
foreach($_SESSION as $name => $value) {
if ($value>0){
if (substr($name, 0, 5)=='cart_') {
$id = substr($name, 5, (strlen($name)-5));
$get = mysql_query('SELECT id, name, price FROM products WHERE id='.mysql_real_escape_string((int)$id));?>
<center>
<table class='menufinal' border=0 width=75%>
<th>Remove Item</th>
<th>Item Name</th>
<th>Item Price</th>
<th>Quantity</th>
<th>Line Total</th>
<?php while ($get_row = mysql_fetch_assoc($get)) {
$sub = $get_row['price']*$value;?>
<tr>
<td><?echo '<img src="x.png"><br>'?></td>
<td><?echo $get_row['name']?></td>
<td><?echo '&pound' . number_format($get_row['price'], 2);?></td>
<td><?echo '- ' .$value. ' +' ?> </td>
<td> <?echo '&pound ' . number_format($sub, 2);?> </td>
</tr>
<?
}
}
if (empty($total)) {
if (empty($sub)) {
//do nothing
} else {
$total = $sub;
}
} else {
$total += $sub;
}
}
}
if (!empty($total)){
echo '<br>Total: &pound' . number_format($total, 2) . '<br>';
echo '<div id="dorc"><p><img src="dishes.png" width="240" height="152"> <img src="spacer.png" width="200"> <img src="checkout.png" width="240" height="152">';
} else {
header ('Location: index.php');
}
}
?>
Currently this code displays:
Change the script as follow. Hope it will work
$value) {
if ($value>0){
if (substr($name, 0, 5)=='cart_') {
$id = substr($name, 5, (strlen($name)-5));
$get = mysql_query('SELECT id, name, price FROM products WHERE id='.mysql_real_escape_string((int)$id));?>
if($i==0)
{
print("
<center>
<table class='menufinal' border=0 width=75%>
<th>Remove Item</th>
<th>Item Name</th>
<th>Item Price</th>
<th>Quantity</th>
<th>Line Total</th>
</tr>
");
}
$i++;
while ($get_row = mysql_fetch_assoc($get)) {
$sub = $get_row['price']*$value;?>
<tr>
<td><?echo '<img src="x.png"><br>'?></td>
<td><?echo $get_row['name']?></td>
<td><?echo '&pound' . number_format($get_row['price'], 2);?></td>
<td><?echo '- ' .$value. ' +' ?> </td>
<td> <?echo '&pound ' . number_format($sub, 2);?> </td>
</tr>
<?
}
}
if (empty($total)) {
if (empty($sub)) {
//do nothing
} else {
$total = $sub;
}
} else {
$total += $sub;
}
}
}
if (!empty($total)){
echo '<br>Total: &pound' . number_format($total, 2) . '<br>';
echo '<div id="dorc"><p><img src="dishes.png" width="240" height="152"> <img src="spacer.png" width="200"> <img src="checkout.png" width="240" height="152">';
} else {
header ('Location: index.php');
}
}
?>
Below is the corrected code, the creation of the table is moved outside of the loop.
Also the table header was added into a tr to create valid html, and also collected data into an $output variable to prevent a bug with your location redirect since data would already be written to the browser (you may vary well still have a problem with this since there is likely other output prior to this cart() function being called.
<?php
function cart() {
$output = '';
$output .= '<center>';
$output .= '<table class='menufinal' border=0 width=75%>';
$output .= '<tr>';
$output .= '<th>Remove Item</th>';
$output .= '<th>Item Name</th>';
$output .= '<th>Item Price</th>';
$output .= '<th>Quantity</th>';
$output .= '<th>Line Total</th>';
$output .= '</tr>';
foreach($_SESSION as $name => $value) {
if ($value>0){
if (substr($name, 0, 5)=='cart_') {
$id = substr($name, 5, (strlen($name)-5));
$get = mysql_query('SELECT id, name, price FROM products WHERE id='.mysql_real_escape_string((int)$id));
while ($get_row = mysql_fetch_assoc($get)) {
$sub = $get_row['price']*$value;
$output .= '<tr>';
$output .= '<td><img src="x.png"><br></td>';
$output .= '<td>' . $get_row['name'] . '</td>';
$output .= '<td>&pound ' . number_format($get_row['price'], 2) . '</td>';
$output .= '<td>- ' .$value. ' +</td>';
$output .= '<td>&pound ' . number_format($sub, 2) . '</td>';
$output .= '</tr>';
}
}
if (empty($total)) {
if (empty($sub)) {
//do nothing
} else {
$total = $sub;
}
} else {
$total += $sub;
}
}
}
$output .= '</table>';
if (empty($total)){
header ('Location: index.php');
exit;
}
$output .= '<br>Total: &pound' . number_format($total, 2) . '<br>';
$output .= '<div id="dorc"><p><img src="dishes.png" width="240" height="152"> <img src="spacer.png" width="200"> <img src="checkout.png" width="240" height="152">';
echo $output;
}
?>

Table Printing in PHP

I have a table showing the list of categories and subcategories, using a function to loop through the parent/child tree. Here is the markup of the script:
<table border="1" width="100%" cellspacing="0" cellpadding="2">
<tr class="dataTableHeadingRow">
<td class="dataTableHeadingContent"><?php echo TABLE_HEADING_PRODUCTS; ?></td>
<td class="dataTableHeadingContent" align="right"><?php echo TABLE_HEADING_TOTAL_WEIGHT; ?> </td>
</tr>
<tr class="dataTableRow">
<td class="dataTableContent">
<?php
function category_list( $category_parent_id = 0 )
{
// NOTE THE ADDITIION OF THE PARENT ID:
$sql = 'select cd.categories_name,c.categories_id, c.parent_id, c.sort_order from ' . TABLE_CATEGORIES . ' c, ' . TABLE_CATEGORIES_DESCRIPTION . ' cd where c.categories_id = cd.categories_id AND c.parent_id='.$category_parent_id;
$res = tep_db_query( $sql );
$cats = array();
while ( $cat = tep_db_fetch_array( $res ) )
{
$cats[] = $cat;
}
if (count($cats) == 0)
{
return '';
}
// populate a list items array
$list_items = array();
$list_items[] = '<ul>';
foreach ( $cats as $cat )
{
// open the list item
$list_items[] = '<li>';
// construct the category link
$list_items[] = $cat['categories_name'];
// recurse into the child list
$list_items[] = category_list( $cat['categories_id'] );
// close the list item
$list_items[] = '</li>';
}
$list_items[] = '</ul>';
// convert to a string
return implode( '', $list_items );
}
echo category_list();
?>
</td>
<td class="dataTableContent"></td>
</tr>
</table>
Instead of printing as a list all in one <td>, how would i print each list element in an individual <td>?
First, remove the php function from the <td> and place it right on top of your table/html.
Instead of echo category_list();, do $list = category_list();
Then within HTML, do this:
<tr class="dataTableRow">
<?php foreach( $list as $v) { ?>
<td class="dataTableContent"><?php echo $v; ?></td>
<?php } ?>
Latest Edit:
<table border="1" width="100%" cellspacing="0" cellpadding="2">
<tr class="dataTableHeadingRow">
<td class="dataTableHeadingContent"><?php echo TABLE_HEADING_PRODUCTS; ?></td>
<td class="dataTableHeadingContent" align="right"><?php echo TABLE_HEADING_TOTAL_WEIGHT; ?> </td>
</tr>
<tr class="dataTableRow"><ul> <!-- change #1 -->
<?php
function category_list( $category_parent_id = 0 )
{
// NOTE THE ADDITIION OF THE PARENT ID:
$sql = 'select cd.categories_name,c.categories_id, c.parent_id, c.sort_order from ' . TABLE_CATEGORIES . ' c, ' . TABLE_CATEGORIES_DESCRIPTION . ' cd where c.categories_id = cd.categories_id AND c.parent_id='.$category_parent_id;
$res = tep_db_query( $sql );
$cats = array();
while ( $cat = tep_db_fetch_array( $res ) )
{
$cats[] = $cat;
}
if (count($cats) == 0)
{
return '';
}
// populate a list items array
$list_items = array();
// $list_items[] = '<ul>'; Change #2
foreach ( $cats as $cat )
{
// open the list item
$list_items[] = '<td class="dataTableContent"><li>'; //Change #3
// construct the category link
$list_items[] = $cat['categories_name'];
// recurse into the child list
$list_items[] = category_list( $cat['categories_id'] );
// close the list item
$list_items[] = '</li></td>'; //Change #4
}
$list_items[] = '</ul></tr>'; //Change #5
// convert to a string
return implode( '', $list_items );
}
echo category_list();
?>
<!--remove </tr> change #6 -->
</table>
Here, I cleaned this up for you. In particular, each function should really only do one thing, so you can keep straight what it's doing. I also removed unnecessary mishegus about your list/implode thing. You're outputting a string, use a string!
<?php
/**
* Gets all categories for a particular parent id.
*/
function get_categories( $category_parent_id = 0 ) {
$sql = 'select cd.categories_name,c.categories_id, c.parent_id, c.sort_order'
.' from ' . TABLE_CATEGORIES . ' c, '
. TABLE_CATEGORIES_DESCRIPTION . ' cd '
.'where c.categories_id = cd.categories_id '
.'AND c.parent_id='.$category_parent_id;
$result = tep_db_query( $sql );//Really should use PDO
$categories = array();//Categories are not chased by dogs. Use full names for your variables!
while ( $category = tep_db_fetch_array( $result ) )
{
$categories[] = $category;
}
return $categories;
}
/**
* Outputs HTML for a list of categories, recursing into them if necessary for more data.
*/
function output_categories($categories, &$output = "") {
if (count($categories) == 0 || empty($categories)) { return; }//either works.
$output =. "<ul>";//change this to <tr> for a table row
foreach ($categories as $category) {
output =. "<li>";//change this to <td> for a table cell
$category['categories_name'];
output_categores(categories($category['categories_id']), $output);
output =. "</li>";//change to </td>
}
$output =. "</ul>";//change to </tr>
return;//Note that $output will be changed by this function.
}
%>
<table border="1" width="100%" cellspacing="0" cellpadding="2">
<tr class="dataTableHeadingRow">
<td class="dataTableHeadingContent"><?php echo TABLE_HEADING_PRODUCTS; ?></td>
<td class="dataTableHeadingContent" align="right"><?php echo TABLE_HEADING_TOTAL_WEIGHT; ?> </td>
</tr>
<tr class="dataTableRow">
<td class="dataTableContent">
<?php
echo output_categories(get_categories());
?>
</td>
<td class="dataTableContent"></td>
</tr>
</table>

How to make 4 items in a row using while loop?

I'm trying to display my products from the database. I'm trying to split it using the if 4%=0, but I can't get it to display 4 items in a row.
Here is my codes:
<table>
<tr>
<?php
include "connect_to_mysql.php";
$split = 0;
$display_all = mysql_query("SELECT * FROM products
ORDER BY FIELD(category, 'ipad','iphone','others')");
while($row=mysql_fetch_array($display_all)) {
$id = $row['id'];
$product_code = $row['product_code'];
$title = $row['title'];
$price = $row['price'];
$split++;
if ($split%4==0){
echo '</tr><tr>';
}
?>
<td>
<table class="normal_text" align="center">
<tr>
<td><a href="product.php?product_id=<?php echo $id?>">
<img width="200px" height="133px" src="products/<?php echo $product_code?>.jpg" />
</a></td>
</tr>
<tr>
<td align="center" style="font-weight:bold"><?php echo $title;?></td>
</tr>
<tr>
<td align="center">$<?php echo $price;?></td>
</tr>
</table>
</td>
<?php
}
?>
</tr>
</table>
You've got the PHP logic before, rather than inside your HTML table output.
Try reorganizing like this:
<?php
include "connect_to_mysql.php";
$split = 0;
$display_all = mysql_query("SELECT * FROM products
ORDER BY FIELD(category, 'ipad','iphone','others')");
?>
<table class="normal_text" align="center">
<tr>
<?php
while($row=mysql_fetch_array($display_all)) {
$id = $row['id'];
$product_code = $row['product_code'];
$title = $row['title'];
$price = $row['price'];
// output product details -- note use of quotes to include PHP vars
$rowHTML = "<td><a href='product.php?product_id=$id'>";
$rowHTML .= "<img width='200px' height='133px' src='products/$product_code.jpg' />";
$rowHTML .= "</a><br/>";
$rowHTML .= "<strong>$title</strong>";
$rowHTML .= "$price</td>";
echo $rowHTML;
$split++;
if ($split%4==0){
echo '</tr><tr>';
}
}
?>
</tr>
</table>
while($row=mysql_fetch_assoc($display_all)) {
$id = $row['id'];
$product_code = $row['product_code'];
$title = $row['title'];
$price = $row['price'];
if ($split % 4 === 0) echo "\n<tr>";
?>
// ONLY <td> CODE </td> here. NO <tr> and NO </table>
<?php
if ($split % 4 === 3) echo "</tr>";
$split++;
}
?>
You are starting and ending at same time and then putting table for each.
You want to start <tr> when %4==0 and end </tr> when %4==3.
Rather than use modulus (%), just add a second variable called $cols, assign it to the amount of columns you want, and compare it. For example:
$rows = 1;
$cols = 4;
$display_all = mysql_query("SELECT * FROM products ORDER BY FIELD(category, 'ipad','iphone','others')");
while($row=mysql_fetch_array($display_all)) {
$id = $row['id'];
$product_code = $row['product_code'];
$title = $row['title'];
$price = $row['price'];
$split++;
if ($rows==$cols){
echo '</tr><tr>';
$rows = 1;
}

Remove empty columns from table drawn using PHP

I've created a size chart using php and mysql for my website. The table is 9 columns wide, however not all columns are always used.
So far I haven't figured out a way to have it skip columns with NA for the column heading. Hoping someone can shed some light on this or point me in the right direction.
Here is the code:
if (!empty($insizes)) {
?>
<div class="ui-widget infoBoxContainer">
<div class="ui-widget-header ui-corner-top infoBoxHeading">
<span><?php $products_name = $product_info['products_name']; echo $products_name; ?> Sizing Chart</span></div>
<table border="0" cellpadding="5" cellspacing="0" id="sizeChart" bgcolor="#ffffff" width="100%">
<tbody width="90%">
<tr>
<td>Size</td>
<?php foreach ($headings as $headingo) { $heading = strtolower(str_replace(" ", "<br>", $headingo)); ?>
<td><?php echo ($product_info["$heading"]); ?></td><?php } ?>
<td>Price</td>
</tr>
<?php
foreach ($insizes as $size)
{
$sizeo = strtolower(str_replace(" ", "", $size));
$sizeo = str_replace("-", "", $sizeo);
?>
<tr>
<td> <?php echo $size; ?></td>
<?php
foreach ($measurements as $measurement) {
$measurementx = $sizeo . '_' . $measurement;
?>
<td><?php echo number_format($product_info["$measurementx"], 0, '.', ''); ?>"<br><span class="sizeChartSm">(<?php echo number_format($product_info["$measurementx"] * 2.54, 1, '.', ''); ?>cm)</span></td>
<?php
}
?>
<td>
<?php
echo $sizeprices["$size"];
?>
</td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
</p>
<?php
}
Thanks a bunch!
Chris
Edit: Here is the rest of the info.
/* <!--- SIZE CHART ---> */
$sizes = array('3X Small', '2X Small', 'X Small', 'Small', 'Medium', 'Large', 'X Large', '2X Large', '3X Large', '4X Large', '5X Large', 'Twin', 'Full', 'Queen', 'King', 'Standard', 'Queen Deep Pocket', 'King Deep Pocket');
$measurements = array('waistmin', 'waistmax', 'legmin', 'legmax', 'crotchwidth', 'maxhip', 'height');
$headings = array ('heading_1', 'heading_2', 'heading_3', 'heading_4', 'heading_5', 'heading_6', 'heading_7',);
$insizes = array();
$sizeprices = array();
/* <!--- END SIZE CHART ---> */
and
/* <!--- SIZE CHART ---> */
$product_info_query = tep_db_query("select
p.products_id, pd.products_name, pd.products_description, p.products_model, p.products_quantity,
p.products_image, pd.products_url, p.products_price, p.products_tax_class_id, p.products_date_added,
p.products_date_available, p.manufacturers_id,
s.*
from
" . TABLE_PRODUCTS . " p,
" . TABLE_PRODUCTS_DESCRIPTION . " pd,
" . products_size_measurements . " s
where
p.products_status = '1' and
p.products_id = '" . (int)$HTTP_GET_VARS['products_id'] . "' and
pd.products_id = p.products_id and
s.product_id = p.products_id and
pd.language_id = '" . (int)$languages_id . "'");
/* <!--- END SIZE CHART ---> */
and
/* <!--- SIZE CHART ---> */
if ($products_options_name['products_options_name'] == 'Size') {
array_push($insizes, $products_options['products_options_values_name']);
}
$products_options_array[] = array(
'id' => $products_options['products_options_values_id'],
'text' => $products_options['products_options_values_name']);
/* $products_options_array[sizeof($products_options_array)-1]['text'] .= ' (' . $products_options[''] . $currencies->display_price($products_options['options_values_price'], tep_get_tax_rate($product_info['products_tax_class_id'])) .') '; */
$final = $products_options['options_values_price'] + $product_info['products_price'];
if ($new_price = tep_get_products_special_price($product_info['products_id'])) {
$price = '<del>' . $currencies->display_price($product_info['products_price'] + $products_options['options_values_price'], tep_get_tax_rate($product_info['products_tax_class_id'])) . '</del> <span class="productSpecialPrice">' . $currencies->display_price($new_price + $products_options['options_values_price'], tep_get_tax_rate($product_info['products_tax_class_id'])) . '</span>';
} else {
$price = $currencies->display_price($final, tep_get_tax_rate($product_info['products_tax_class_id']));
}
$name = $products_options['products_options_values_name'];
$sizeprices = array_push_assoc($sizeprices, "$name", "$price");
/* <!--- END SIZE CHART ---> */
Shouldn't I be able to use an if, else statement using flags (such as NA and 0) for the data stored in the DB? Something like so:
<?php if ($heading != "NA") {?>
<td><?php echo ($product_info["$heading"]); ?></td><?php }} else { ?>
<td>Price</td>
</tr>
<?php } ?>
and
<?php if ($measurement != 0) {?>
<td><?php echo number_format($product_info["$measurementx"], 0, '.', ''); ?>"<br><span class="sizeChartSm">(<?php echo number_format($product_info["$measurementx"] * 2.54, 1, '.', ''); ?>cm)</span></td>
<?php
}} else {
?>
<td>
<?php
echo $sizeprices["$size"];
?>
</td>
</tr>
<?php
}}
?>
However I can't seem to get the syntax right and keep throwing T_ELSE errors.
I think your error is coming from having too many brackets for the if else statement. Try this:
<?php if ($measurement != 0) {?>
<td><?php echo number_format($product_info["$measurementx"], 0, '.', ''); ?>"<br><span class="sizeChartSm">(<?php echo number_format($product_info["$measurementx"] * 2.54, 1, '.', ''); ?>cm)</span></td>
<?php
} else {
?>
<td>
<?php
echo $sizeprices["$size"];
?>
</td>
</tr>
<?php
}
?>
Also, your code would look way cleaner if you used short tags to echo your variables in the table like so:
<?php if ($measurement != 0) {?>
<td>
<?=number_format($product_info["$measurementx"], 0, '.', '')?>
<br>
<span class="sizeChartSm">
(<?=number_format($product_info["$measurementx"] * 2.54, 1, '.', '')?>cm)
</span>
</td>
<?php } else { ?>
<td>
<?=$sizeprices["$size"]?>
</td>
</tr>
<?php } ?>
skipping columns will cause the table to be drawn incorrectly.
<table>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td>1</td>
... skipped
<td>3</td>
</tr>
would render as
1 2 3
1 3
not
1 2 3
1 3
You should modify $headings and $insizes to hide some of the columns or change the logic of your script. But I think for you will be easy to modify the arrays that you use to genertate the table.. Please show how you build these 2 arrays.

PHP - How can I insert multiple items from a shopping cart into the database?

I'd like to apologize in advance if this question has been asked before. I've been surfing this website for a couple of hours trying to find the answer I'm looking for but no luck.
Here's my problem:
I've created this online shopping cart based on a tutorial from a book by Larry Ullman (PHP and MySQL for Dynamic Websites Edition 1). Everything worked well until i realized that the writer stopped at the checkout.php
I need help coding the checkout page. My biggest problem is inserting multiple products from the shopping cart into the database as individual rows.
Can anyone help?
Thanks.
Here's what i have so far:
<?php
session_start();
if (is_numeric ($_GET['pid'])) {
$pid = $_GET['pid'];
if (isset ($_SESSION['cart'][$pid])) {
$qty = $_SESSION['cart'][$pid] + 1;
} else {
$qty = 1;
}
$_SESSION['cart'][$pid] = $qty;
echo '<p>The item has been added to your shopping cart.</p>';
}
if (isset ($_POST['submit'])) {
foreach ($_POST['qty'] as $key => $value) {
if ( ($value == 0) AND (is_numeric ($value)) ) {
unset ($_SESSION['cart'][$key]);
} elseif ( is_numeric ($value) AND ($value > 0) ) {
$_SESSION['cart'][$key] = $value;
}
}
}
$empty = TRUE;
if (isset ($_SESSION['cart'])) {
foreach ($_SESSION['cart'] as $key => $value) {
if (isset($value)) {
$empty = FALSE;
}
}
}
if (!$empty) {
include("config.php");
$query = 'SELECT * FROM buds_customer, buds_product WHERE buds_customer.customer_id = buds_product.customer_id AND buds_product.print_id IN (';
foreach ($_SESSION['cart'] as $key => $value) {
$query .= $key . ',';
}
$query = substr ($query, 0, -1) . ') ORDER BY buds_customer.last ASC';
$result = mysql_query ($query);
echo '<table border="0" width="90%" cellspacing="3" cellpadding="3" align="center">
<tr>
<td align="left" width="30%"><b>Seller</b></td>
<td align="left" width="30%"><b>Product</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>
<form action="view_cart.php" method="post">
';
$total = 0; // Total cost of the order.
while ($row = mysql_fetch_array ($result, MYSQL_ASSOC)) {
$subtotal = $_SESSION['cart'][$row['print_id']] * $row['price'];
$total += $subtotal;
echo " <tr>
<td align=\"left\"><input type=\"text\" name=\"seller\" value=\" {$row['first']} {$row['last']}\"></td>
<td align=\"left\"><input type=\"text\" name=\"product\" value=\" {$row['product']}\"></td>
<td align=\"right\"><input type=\"text\" name=\"price\" value=\" {$row['price']}\"></td>
<td align=\"center\"><input type=\"text\" size=\"3\" name=\"qty[{$row['print_id']}]\" value=\"{$_SESSION['cart'][$row['print_id']]}\" /></td>
<td align=\"right\"><input type=\"text\" name=\"subtotal\" value=\"" . number_format ($subtotal, 2) . "\"></td>
</tr>\n";
}
echo ' <tr>
<td colspan="4" align="right"><b>Total:<b></td>
<td align="right"><input type="text" size="3" name="total" value="' . number_format ($total, 2) . '"></td>
</tr>
</table><div align="center"><input type="submit" name="submit" value="Update My Cart" /></form><br /><br /><center>Checkout</center></div>
';
} else {
echo mysql_error();
}
?>
Your example doesn't show any insert statements at all... You should lookup and learn INSERT INTO (http://www.w3schools.com/php/php_mysql_insert.asp). Then you will end up have a foreach loop... the basic code will end up looking something like this:
foreach ($items as $item) {
$sql = 'INSERT INTO `order_history` (`productid`, `productqty`)'
. ' VALUES ($item['product_id'], $item['product_qty']);
mysql_query($sql);
}
Of course I'm leaving out error checking and all kinds of extra fields you will want to populate... but you get the idea. Good luck!

Categories