Remove empty columns from table drawn using PHP - 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.

Related

php echo in html table

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>

How to Show Order Details on Checkout Success Page in Opencart 2x

I am trying to show order details for successful orders on success page but unable to do so. Another answer here suggests to modify success.php and success.tpl but it's not working on Opencart 2.
What have I tried?
catalog/controller/checkout/success.php
and added new lines in the following code:
public function index() {
$this->data['order_id'] = 0; // <-- NEW LINE
$this->data['total'] = 0; // <-- NEW LINE
if (isset($this->session->data['order_id'])) {
$this->data['order_id'] = $this->session->data['order_id']; // <-- NEW LINE
$this->data['total'] = $this->cart->getTotal(); // <-- NEW LINE
$this->cart->clear();
unset($this->session->data['shipping_method']);
unset($this->session->data['shipping_methods']);
unset($this->session->data['payment_method']);
unset($this->session->data['payment_methods']);
unset($this->session->data['guest']);
unset($this->session->data['comment']);
unset($this->session->data['order_id']);
unset($this->session->data['coupon']);
unset($this->session->data['reward']);
unset($this->session->data['voucher']);
unset($this->session->data['vouchers']);
}
$this->language->load('checkout/success');
Now added the following code into success.tpl
<?php if($order_id) { ?>
<script type="text/javascript">
// Some code here
arr.push([
"create_order",
{order_id: '<?php echo $order_id; ?>', sum: '<?php echo $total; ?>'}
]);
But it doesn't show anything on success page. The above code is to show order ID and total but I want to show all details of order including name, address, products, total, shipping, etc. Just like in the order invoice.
Any help will be appreciated. Thank you
What I did on pre 2.0 versions was to actually set a new variable to the session for the order id as I found that $this->session->data['order_id'] wasn't consistent and sometimes was getting unset by the time the user reached ControllerCheckoutSuccess.
If you'd like to use this approach, edit your catalog/model/checkout/order.php file. At or about line 302 (within the addOrderHistory method) you'll see where the script checks for order status ids to determine if it should complete the order.
Within that statement, set a new session variable of your choice to the order id passed in, perhaps $this->session->data['customer_order_id'] = $order_id
Now you have a session variable that you know will remain consistent since you've created it yourself and OpenCart won't mess with it.
If you're finding that the session order id IS remaining consistent in 2.1 > then don't worry about this, just go ahead and use the default session order id variable built in.
The next step will be for you to decide how you want your invoice data loaded, via PHP or Ajax. I wouldn't recommend using Ajax as since this could be manipulated with browser developer tools and may expose other's customer's information. By using PHP and the session you eliminate this risk since a random hacker won't have access to another customer's session.
REQUIRED FOR BOTH OPTIONS BELOW:
Open catalog/controller/checkout/success.php
Right after the language file is loaded in your index method add the following:
$order_id = false;
// If NOT using the custom variable mentioned SKIP this
if (isset($this->session->data['customer_order_id'])) {
$order_id = $this->session->data['customer_order_id'];
}
If you're using the baked in session data order id, set your order id within that statement:
if (isset($this->session->data['order_id'])) {
$this->cart->clear();
$order_id = $this->session->data['order_id'];
OPTION 1:
Add receipt data to checkout/success.
Find this line:
$data['button_continue'] = $this->language->get('button_continue');
Should be around line 77-84 or thereabout.
Here you'll load up and format all your receipt info.
Open catalog/controller/account/order.php
On line 108 you'll find the info method.
Here's where the fun starts :P
Copy all the relevant info from that method into your checkout success controller just after the $data['button_continue'] = $this->language->get('button_continue'); line mentioned above.
You'll need to go through this line by line and tweak it because remember this is designed for logged in customers, so you won't want links for returns or reorders etc.
Next you're going to want to make a new template because the common/success template is generic and used all over the place.
Copy catalog/view/theme/(your theme)/template/common/success.tpl
to: catalog/view/theme/(your theme)/template/checkout/success.tpl
Open catalog/view/theme/default/template/account/order_info.tpl
The tables you'll need to add to your success template start on line 28 and extend to line 139. If you're using a different theme, you'll need to suss this out for yourself.
Don't forget to change the path to your template in your checkout/success controller to your new checkout/success tpl file.
NOTE:
It's important to remember that all this SHOULD be done in a modification package and NOT in your core files, but I don't know your situation so that's up to you to decide.
OPTION 2:
Create your own module.
In my opinion having built for this system since version 1.4 this is the best option.
Create new controller in modules, let's call it ControllerModuleReceipt:
<?php
/**
* Controller class for displaying a receipt on checkout success.
*/
class ControllerModuleReceipt extends Controller
{
/**
* Replicates the ControllerAccountOrder::info
* method for displaying order info in our
* ControllerCheckoutSuccess::index method
*
* #param int $order_id our order id
* #return mixed receipt view
*/
public function index($setting)
{
$this->load->language('account/order');
$this->load->model('account/order');
if (empty($setting['order_id'])) {
return;
}
$order_id = $setting['order_id'];
$order_info = $this->model_account_order->getOrder($order_id);
if ($order_info) {
$data['text_order_detail'] = $this->language->get('text_order_detail');
$data['text_invoice_no'] = $this->language->get('text_invoice_no');
$data['text_order_id'] = $this->language->get('text_order_id');
$data['text_date_added'] = $this->language->get('text_date_added');
$data['text_shipping_method'] = $this->language->get('text_shipping_method');
$data['text_shipping_address'] = $this->language->get('text_shipping_address');
$data['text_payment_method'] = $this->language->get('text_payment_method');
$data['text_payment_address'] = $this->language->get('text_payment_address');
$data['text_history'] = $this->language->get('text_history');
$data['text_comment'] = $this->language->get('text_comment');
$data['column_name'] = $this->language->get('column_name');
$data['column_model'] = $this->language->get('column_model');
$data['column_quantity'] = $this->language->get('column_quantity');
$data['column_price'] = $this->language->get('column_price');
$data['column_total'] = $this->language->get('column_total');
$data['column_action'] = $this->language->get('column_action');
$data['column_date_added'] = $this->language->get('column_date_added');
$data['column_status'] = $this->language->get('column_status');
$data['column_comment'] = $this->language->get('column_comment');
$data['invoice_no'] = '';
if ($order_info['invoice_no']) {
$data['invoice_no'] = $order_info['invoice_prefix'] . $order_info['invoice_no'];
}
$data['order_id'] = $order_id;
$data['date_added'] = date($this->language->get('date_format_short'), strtotime($order_info['date_added']));
$format = '{firstname} {lastname}' . "\n" . '{company}' . "\n" . '{address_1}' . "\n" . '{address_2}' . "\n" . '{city} {postcode}' . "\n" . '{zone}' . "\n" . '{country}';
if ($order_info['payment_address_format']) {
$format = $order_info['payment_address_format'];
}
$find = array(
'{firstname}',
'{lastname}',
'{company}',
'{address_1}',
'{address_2}',
'{city}',
'{postcode}',
'{zone}',
'{zone_code}',
'{country}'
);
$replace = array(
'firstname' => $order_info['payment_firstname'],
'lastname' => $order_info['payment_lastname'],
'company' => $order_info['payment_company'],
'address_1' => $order_info['payment_address_1'],
'address_2' => $order_info['payment_address_2'],
'city' => $order_info['payment_city'],
'postcode' => $order_info['payment_postcode'],
'zone' => $order_info['payment_zone'],
'zone_code' => $order_info['payment_zone_code'],
'country' => $order_info['payment_country']
);
$data['payment_address'] = str_replace(array("\r\n", "\r", "\n"), '<br />', preg_replace(array("/\s\s+/", "/\r\r+/", "/\n\n+/"), '<br />', trim(str_replace($find, $replace, $format))));
$data['payment_method'] = $order_info['payment_method'];
$format = '{firstname} {lastname}' . "\n" . '{company}' . "\n" . '{address_1}' . "\n" . '{address_2}' . "\n" . '{city} {postcode}' . "\n" . '{zone}' . "\n" . '{country}';
if ($order_info['shipping_address_format']) {
$format = $order_info['shipping_address_format'];
}
$find = array(
'{firstname}',
'{lastname}',
'{company}',
'{address_1}',
'{address_2}',
'{city}',
'{postcode}',
'{zone}',
'{zone_code}',
'{country}'
);
$replace = array(
'firstname' => $order_info['shipping_firstname'],
'lastname' => $order_info['shipping_lastname'],
'company' => $order_info['shipping_company'],
'address_1' => $order_info['shipping_address_1'],
'address_2' => $order_info['shipping_address_2'],
'city' => $order_info['shipping_city'],
'postcode' => $order_info['shipping_postcode'],
'zone' => $order_info['shipping_zone'],
'zone_code' => $order_info['shipping_zone_code'],
'country' => $order_info['shipping_country']
);
$data['shipping_address'] = str_replace(array("\r\n", "\r", "\n"), '<br />', preg_replace(array("/\s\s+/", "/\r\r+/", "/\n\n+/"), '<br />', trim(str_replace($find, $replace, $format))));
$data['shipping_method'] = $order_info['shipping_method'];
$this->load->model('catalog/product');
$this->load->model('tool/upload');
// Products
$data['products'] = array();
$products = $this->model_account_order->getOrderProducts($this->request->get['order_id']);
foreach ($products as $product) {
$option_data = array();
$options = $this->model_account_order->getOrderOptions($this->request->get['order_id'], $product['order_product_id']);
foreach ($options as $option) {
$value = false;
if ($option['type'] == 'file') {
$upload_info = $this->model_tool_upload->getUploadByCode($option['value']);
if ($upload_info) {
$value = $upload_info['name'];
}
}
if (! $value) {
$value = $option['value'];
}
$option_data[] = array(
'name' => $option['name'],
'value' => (utf8_strlen($value) > 20 ? utf8_substr($value, 0, 20) . '..' : $value)
);
}
$product_info = $this->model_catalog_product->getProduct($product['product_id']);
$data['products'][] = array(
'name' => $product['name'],
'model' => $product['model'],
'option' => $option_data,
'quantity' => $product['quantity'],
'price' => $this->currency->format($product['price'] + ($this->config->get('config_tax') ? $product['tax'] : 0), $order_info['currency_code'], $order_info['currency_value']),
'total' => $this->currency->format($product['total'] + ($this->config->get('config_tax') ? ($product['tax'] * $product['quantity']) : 0), $order_info['currency_code'], $order_info['currency_value'])
);
}
// Voucher
$data['vouchers'] = array();
$vouchers = $this->model_account_order->getOrderVouchers($this->request->get['order_id']);
foreach ($vouchers as $voucher) {
$data['vouchers'][] = array(
'description' => $voucher['description'],
'amount' => $this->currency->format($voucher['amount'], $order_info['currency_code'], $order_info['currency_value'])
);
}
// Totals
$data['totals'] = array();
$totals = $this->model_account_order->getOrderTotals($this->request->get['order_id']);
foreach ($totals as $total) {
$data['totals'][] = array(
'title' => $total['title'],
'text' => $this->currency->format($total['value'], $order_info['currency_code'], $order_info['currency_value']),
);
}
$data['comment'] = nl2br($order_info['comment']);
if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/module/receipt.tpl')) {
return $this->load->view($this->config->get('config_template') . '/template/module/receipt.tpl', $data);
} else {
return $this->load->view('default/template/module/receipt.tpl', $data);
}
}
}
}
TEMPLATE:
Next let's create the template in catalog/views/theme/default/module/receipt.tpl
<table class="table table-bordered table-hover">
<thead>
<tr>
<td class="text-left" colspan="2"><?= $text_order_detail; ?></td>
</tr>
</thead>
<tbody>
<tr>
<td class="text-left" style="width: 50%;"><?php if ($invoice_no): ?>
<b><?= $text_invoice_no; ?></b> <?= $invoice_no; ?><br />
<?php endif; ?>
<b><?= $text_order_id; ?></b> #<?= $order_id; ?><br />
<b><?= $text_date_added; ?></b> <?= $date_added; ?></td>
<td class="text-left"><?php if ($payment_method): ?>
<b><?= $text_payment_method; ?></b> <?= $payment_method; ?><br />
<?php endif; ?>
<?php if ($shipping_method): ?>
<b><?= $text_shipping_method; ?></b> <?= $shipping_method; ?>
<?php endif; ?></td>
</tr>
</tbody>
</table>
<table class="table table-bordered table-hover">
<thead>
<tr>
<td class="text-left" style="width: 50%;"><?= $text_payment_address; ?></td>
<?php if ($shipping_address): ?>
<td class="text-left"><?= $text_shipping_address; ?></td>
<?php endif; ?>
</tr>
</thead>
<tbody>
<tr>
<td class="text-left"><?= $payment_address; ?></td>
<?php if ($shipping_address): ?>
<td class="text-left"><?= $shipping_address; ?></td>
<?php endif; ?>
</tr>
</tbody>
</table>
<div class="table-responsive">
<table class="table table-bordered table-hover">
<thead>
<tr>
<td class="text-left"><?= $column_name; ?></td>
<td class="text-left"><?= $column_model; ?></td>
<td class="text-right"><?= $column_quantity; ?></td>
<td class="text-right"><?= $column_price; ?></td>
<td class="text-right"><?= $column_total; ?></td>
<?php if ($products): ?>
<td style="width: 20px;"></td>
<?php endif; ?>
</tr>
</thead>
<tbody>
<?php foreach ($products as $product): ?>
<tr>
<td class="text-left"><?= $product['name']; ?>
<?php foreach ($product['option'] as $option): ?>
<br />
<small> - <?= $option['name']; ?>: <?= $option['value']; ?></small>
<?php endforeach; ?></td>
<td class="text-left"><?= $product['model']; ?></td>
<td class="text-right"><?= $product['quantity']; ?></td>
<td class="text-right"><?= $product['price']; ?></td>
<td class="text-right"><?= $product['total']; ?></td>
<td class="text-right" style="white-space: nowrap;"><?php if ($product['reorder']): ?>
<i class="fa fa-shopping-cart"></i>
<?php endif; ?>
<i class="fa fa-reply"></i></td>
</tr>
<?php endforeach; ?>
<?php foreach ($vouchers as $voucher): ?>
<tr>
<td class="text-left"><?= $voucher['description']; ?></td>
<td class="text-left"></td>
<td class="text-right">1</td>
<td class="text-right"><?= $voucher['amount']; ?></td>
<td class="text-right"><?= $voucher['amount']; ?></td>
<?php if ($products): ?>
<td></td>
<?php endif; ?>
</tr>
<?php endforeach; ?>
</tbody>
<tfoot>
<?php foreach ($totals as $total): ?>
<tr>
<td colspan="3"></td>
<td class="text-right"><b><?= $total['title']; ?></b></td>
<td class="text-right"><?= $total['text']; ?></td>
<?php if ($products): ?>
<td></td>
<?php endif; ?>
</tr>
<?php endforeach; ?>
</tfoot>
</table>
</div>
<?php if ($comment): ?>
<table class="table table-bordered table-hover">
<thead>
<tr>
<td class="text-left"><?= $text_comment; ?></td>
</tr>
</thead>
<tbody>
<tr>
<td class="text-left"><?= $comment; ?></td>
</tr>
</tbody>
</table>
<?php endif; ?>
Once again, if using your own theme you'll need to adjust this.
ADD MODULE TO CHECKOUT SUCCESS
Back in the checkout success controller we need to add the module.
Find $data['content_bottom'] = $this->load->controller('common/content_bottom');
After that line add this:
$data['receipt'] = false;
if ($order_id) {
$data['receipt'] = $this->load->controller('module/receipt', array('order_id' => $order_id));
}
ADD TO SUCCESS TEMPLATE
Open catalog/view/theme/default/common/success.tpl
After <?php echo $text_message; ?> add:
<?php if ($receipt): ?>
<?= $receipt; ?>
<?php endif; ?>
And that should be it. Once again it's best to add the changes to core files via a modification, but by creating your own module it's MUCH easier to add a modification, much less to deal with.
I haven't tested the code above but it should work or have minimal errors. Feel free to post any errors and I'll be happy to help fix them.
The awesome code that Vince post works!
But I found some Errors and PHP Notices and product table was not showing up, so i did some modifications in the code and it works 100% now.
I used the OPTION 2 and Opencart 2.2 for the tests.
Here is the code:
Receipit.php in CONTROLLER/MODULE
<?php
/**
* Controller class for displaying a receipt on checkout success.
*/
class ControllerModuleReceipt extends Controller
{
/**
* Replicates the ControllerAccountOrder::info
* method for displaying order info in our
* ControllerCheckoutSuccess::index method
*
* #param int $order_id our order id
* #return mixed receipt view
*/
public function index($setting)
{
$this->load->language('account/order');
$this->load->model('account/order');
if (empty($setting['order_id'])) {
return;
}
$order_id = $setting['order_id'];
$order_info = $this->model_account_order->getOrder($order_id);
if ($order_info) {
$data['text_order_detail'] = $this->language->get('text_order_detail');
$data['text_invoice_no'] = $this->language->get('text_invoice_no');
$data['text_order_id'] = $this->language->get('text_order_id');
$data['text_date_added'] = $this->language->get('text_date_added');
$data['text_shipping_method'] = $this->language->get('text_shipping_method');
$data['text_shipping_address'] = $this->language->get('text_shipping_address');
$data['text_payment_method'] = $this->language->get('text_payment_method');
$data['text_payment_address'] = $this->language->get('text_payment_address');
$data['text_history'] = $this->language->get('text_history');
$data['text_comment'] = $this->language->get('text_comment');
$data['column_name'] = $this->language->get('column_name');
$data['column_model'] = $this->language->get('column_model');
$data['column_quantity'] = $this->language->get('column_quantity');
$data['column_price'] = $this->language->get('column_price');
$data['column_total'] = $this->language->get('column_total');
$data['column_action'] = $this->language->get('column_action');
$data['column_date_added'] = $this->language->get('column_date_added');
$data['column_status'] = $this->language->get('column_status');
$data['column_comment'] = $this->language->get('column_comment');
$data['invoice_no'] = '';
if ($order_info['invoice_no']) {
$data['invoice_no'] = $order_info['invoice_prefix'] . $order_info['invoice_no'];
}
$data['order_id'] = $order_id;
$data['date_added'] = date($this->language->get('date_format_short'), strtotime($order_info['date_added']));
$format = '{firstname} {lastname}' . "\n" . '{company}' . "\n" . '{address_1}' . "\n" . '{address_2}' . "\n" . '{city} {postcode}' . "\n" . '{zone}' . "\n" . '{country}';
if ($order_info['payment_address_format']) {
$format = $order_info['payment_address_format'];
}
$find = array(
'{firstname}',
'{lastname}',
'{company}',
'{address_1}',
'{address_2}',
'{city}',
'{postcode}',
'{zone}',
'{zone_code}',
'{country}'
);
$replace = array(
'firstname' => $order_info['payment_firstname'],
'lastname' => $order_info['payment_lastname'],
'company' => $order_info['payment_company'],
'address_1' => $order_info['payment_address_1'],
'address_2' => $order_info['payment_address_2'],
'city' => $order_info['payment_city'],
'postcode' => $order_info['payment_postcode'],
'zone' => $order_info['payment_zone'],
'zone_code' => $order_info['payment_zone_code'],
'country' => $order_info['payment_country']
);
$data['payment_address'] = str_replace(array("\r\n", "\r", "\n"), '<br />', preg_replace(array("/\s\s+/", "/\r\r+/", "/\n\n+/"), '<br />', trim(str_replace($find, $replace, $format))));
$data['payment_method'] = $order_info['payment_method'];
$format = '{firstname} {lastname}' . "\n" . '{company}' . "\n" . '{address_1}' . "\n" . '{address_2}' . "\n" . '{city} {postcode}' . "\n" . '{zone}' . "\n" . '{country}';
if ($order_info['shipping_address_format']) {
$format = $order_info['shipping_address_format'];
}
$find = array(
'{firstname}',
'{lastname}',
'{company}',
'{address_1}',
'{address_2}',
'{city}',
'{postcode}',
'{zone}',
'{zone_code}',
'{country}'
);
$replace = array(
'firstname' => $order_info['shipping_firstname'],
'lastname' => $order_info['shipping_lastname'],
'company' => $order_info['shipping_company'],
'address_1' => $order_info['shipping_address_1'],
'address_2' => $order_info['shipping_address_2'],
'city' => $order_info['shipping_city'],
'postcode' => $order_info['shipping_postcode'],
'zone' => $order_info['shipping_zone'],
'zone_code' => $order_info['shipping_zone_code'],
'country' => $order_info['shipping_country']
);
$data['shipping_address'] = str_replace(array("\r\n", "\r", "\n"), '<br />', preg_replace(array("/\s\s+/", "/\r\r+/", "/\n\n+/"), '<br />', trim(str_replace($find, $replace, $format))));
$data['shipping_method'] = $order_info['shipping_method'];
$this->load->model('catalog/product');
$this->load->model('tool/upload');
// Products
$data['products'] = array();
$products = $this->model_account_order->getOrderProducts($order_id);
foreach ($products as $product) {
$option_data = array();
$options = $this->model_account_order->getOrderOptions($order_id, $product['order_product_id']);
foreach ($options as $option) {
$value = false;
if ($option['type'] == 'file') {
$upload_info = $this->model_tool_upload->getUploadByCode($option['value']);
if ($upload_info) {
$value = $upload_info['name'];
}
}
if (! $value) {
$value = $option['value'];
}
$option_data[] = array(
'name' => $option['name'],
'value' => (utf8_strlen($value) > 20 ? utf8_substr($value, 0, 20) . '..' : $value)
);
}
$product_info = $this->model_catalog_product->getProduct($product['product_id']);
$data['products'][] = array(
'name' => $product['name'],
'model' => $product['model'],
'option' => $option_data,
'quantity' => $product['quantity'],
'price' => $this->currency->format($product['price'] + ($this->config->get('config_tax') ? $product['tax'] : 0), $order_info['currency_code'], $order_info['currency_value']),
'total' => $this->currency->format($product['total'] + ($this->config->get('config_tax') ? ($product['tax'] * $product['quantity']) : 0), $order_info['currency_code'], $order_info['currency_value'])
);
}
// Voucher
$data['vouchers'] = array();
$vouchers = $this->model_account_order->getOrderVouchers($order_id);
foreach ($vouchers as $voucher) {
$data['vouchers'][] = array(
'description' => $voucher['description'],
'amount' => $this->currency->format($voucher['amount'], $order_info['currency_code'], $order_info['currency_value'])
);
}
// Totals
$data['totals'] = array();
$totals = $this->model_account_order->getOrderTotals($order_id);
foreach ($totals as $total) {
$data['totals'][] = array(
'title' => $total['title'],
'text' => $this->currency->format($total['value'], $order_info['currency_code'], $order_info['currency_value']),
);
}
$data['comment'] = nl2br($order_info['comment']);
if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/module/receipt.tpl')) {
return $this->load->view($this->config->get('config_template') . '/template/module/receipt.tpl', $data);
} else {
return $this->load->view('/module/receipt.tpl', $data);
}
}
}
}
Receipit.tpl in TEMPLATES/MODULE
<table class="table table-bordered table-hover">
<thead>
<tr>
<td class="text-left" colspan="2"><?= $text_order_detail; ?></td>
</tr>
</thead>
<tbody>
<tr>
<td class="text-left" style="width: 50%;"><?php if ($invoice_no): ?>
<b><?= $text_invoice_no; ?></b> <?= $invoice_no; ?><br />
<?php endif; ?>
<b><?= $text_order_id; ?></b> #<?= $order_id; ?><br />
<b><?= $text_date_added; ?></b> <?= $date_added; ?></td>
<td class="text-left"><?php if ($payment_method): ?>
<b><?= $text_payment_method; ?></b> <?= $payment_method; ?><br />
<?php endif; ?>
<?php if ($shipping_method): ?>
<b><?= $text_shipping_method; ?></b> <?= $shipping_method; ?>
<?php endif; ?></td>
</tr>
</tbody>
</table>
<table class="table table-bordered table-hover">
<thead>
<tr>
<td class="text-left" style="width: 50%;"><?= $text_payment_address; ?></td>
<?php if ($shipping_address): ?>
<td class="text-left"><?= $text_shipping_address; ?></td>
<?php endif; ?>
</tr>
</thead>
<tbody>
<tr>
<td class="text-left"><?= $payment_address; ?></td>
<?php if ($shipping_address): ?>
<td class="text-left"><?= $shipping_address; ?></td>
<?php endif; ?>
</tr>
</tbody>
</table>
<div class="table-responsive">
<table class="table table-bordered table-hover">
<thead>
<tr>
<td class="text-left" style="display: table-cell"><?= $column_name; ?></td>
<td class="text-left" style="display: none"><?= $column_model; ?></td>
<td class="text-right" style="display: table-cell"><?= $column_quantity; ?></td>
<td class="text-right" style="display: table-cell"><?= $column_price; ?></td>
<td class="text-right" style="display: table-cell"><?= $column_total; ?></td>
</tr>
</thead>
<tbody>
<?php foreach ($products as $product): ?>
<tr>
<td class="text-left" style="display: table-cell"><?= $product['name']; ?>
<?php foreach ($product['option'] as $option): ?>
<br />
<small> - <?= $option['name']; ?>: <?= $option['value']; ?></small>
<?php endforeach; ?></td>
<td class="text-left" style="display: none"><?= $product['model']; ?></td>
<td class="text-right" style="display: table-cell"><?= $product['quantity']; ?></td>
<td class="text-right" style="display: table-cell"><?= $product['price']; ?></td>
<td class="text-right" style="display: table-cell"><?= $product['total']; ?></td>
</tr>
<?php endforeach; ?>
<?php foreach ($vouchers as $voucher): ?>
<tr>
<td class="text-left"><?= $voucher['description']; ?></td>
<td class="text-left"></td>
<td class="text-right">1</td>
<td class="text-right"><?= $voucher['amount']; ?></td>
<td class="text-right"><?= $voucher['amount']; ?></td>
</tr>
<?php endforeach; ?>
</tbody>
<tfoot>
<?php foreach ($totals as $total): ?>
<tr>
<td colspan="2"></td>
<td class="text-right"><b><?= $total['title']; ?></b></td>
<td class="text-right"><?= $total['text']; ?></td>
</tr>
<?php endforeach; ?>
</tfoot>
</table>
</div>
<?php if ($comment): ?>
<table class="table table-bordered table-hover">
<thead>
<tr>
<td class="text-left"><?= $text_comment; ?></td>
</tr>
</thead>
<tbody>
<tr>
<td class="text-left"><?= $comment; ?></td>
</tr>
</tbody>
</table>
<?php endif; ?>
NOTE
Before entering the codes in your store, test on a backup to make sure that your store will not be impaired.
If this code has any flaws, please let me know here
Thanks!

Exporting to .csv from a php table, without creating a new sql table

For a project i have to export a report I made to a file location.It has to be .csv file format and needs to contain the headings
<html>
<?php
$profiles = new CGenRs("SELECT * from adapt_profile ", $database);
$profiles->first();
$users = new CGenRs("SELECT * from authuser where userno in (select user_number from adapt_profile_time where exported = 'f')", $database);
$users->first();
$logtime = new CGenRs("SELECT time_id,
profile_id ,
user_number ,
start_time ,
end_time,
description,
exported, EXTRACT(hour FROM(end_time - start_time)) as diff from adapt_profile_time where exported = 'f' order by user_number", $database);
$logtime->first();
$timestamp = new CGenRS("SELECT EXTRACT(minute FROM(end_time - start_time))as difference FROM adapt_profile_time WHERE exported='f'", $database);
$timestamp->first();
?>
<table width="100%" >
<tr>
<th align="left">USER NAME</th>
<th align="left">WORKED FROM</th>
<th align="left">WORKED TO</th>
<th align="left">TOTAL</th>
<th align="left">FOR PROFILE</th>
<th align="left">DESCRIPTION</th>
</tr>
<?php
$curr_userno = $logtime->valueof('user_number');
$tot_mins = 0;
while (!$logtime->eof()) {
while (!$timestamp->eof()) {
if ($curr_userno != $logtime->valueof('user_number')) {
$total_time = floor($tot_mins / 60) . " hours " . ($tot_mins % 60)." minutes"
?>
<tr>
<td></td>
<td></td>
<td align="right"><b>Total =</b></td>
<td colspan="8"><b><?php echo $total_time; ?></b></td>
<td></td>
<td></td>
</tr>
<?php
$curr_userno = $logtime->valueof('user_number');
$tot_mins = 0;
}
$tot_mins = ($tot_mins + $logtime->valueof('diff') * 60) + $timestamp->valueof('difference');
?>
<tr>
<td>
<?php
while (!$users->eof()) {
if ($users->valueof('userno') == $logtime->valueof('user_number')) {
echo $users->valueof('auth_name') . ' ' . $users->valueof('auth_surname');
$users->first();
break;
}
$users->next();
}
?>
</td>
<td><?php echo $logtime->valueof('start_time') ?></td>
<td><?php echo $logtime->valueof('end_time') ?></td>
<td><?php echo $logtime->valueof('diff') . " " . "hours" . " " . $timestamp->valueof('difference') . " " . "minutes"; ?></td>
<td>
<?php
while (!$profiles->eof()) {
if ($profiles->valueof('profile_id') == $logtime->valueof('profile_id')) {
echo $profiles->valueof('profile_name');
$profiles->first();
break;
}
$profiles->next();
}
?>
</td>
<td><?php echo $logtime->valueof('description') ?></td>
</tr>
<?php
$timestamp->next();
$logtime->next();
}
echo "<hr></hr>";
}
$total_time = floor($tot_mins / 60) . " hours " . ($tot_mins % 60)." minutes";
?>
<tr>
<td> </td>
<td></td>
<td align="right"><b>Total =</b></td>
<td colspan="8"><b><?php echo $total_time; ?></b></td>
<td></td>
<td></td>
</tr>
<?php
?>
<tr>
<td colspan="8"><hr></hr></td>
</tr>
</table>
<form id="submit_form" action="" method="post" name="sbt_frm" align="center">
<input align="center" id="sbt_btn" type="submit" value="Export" name="sbt_btn"></input>
</form>
</html>
Above is a report i have generated from a previous page that inputs work times and dates. I would like to have the bottom form export the page/report i have made into a .csv to "location/x" when the export button is pressed.How would I go about this. Using POSTGRESQL
I only need to know what query or command to use or look into, Will do the further research and then post feedback
This may be a good start (using Javascript/JQuery), adapted from sources cited within demo code:
JSFiddle demo here. Note: Fiddled version may not work in IE - try FF or Chrome.
Here's how I extracted table data into a string using javascript:
var $rows = $table.find('tr:has(td)'),
// Temporary delimiter characters to avoid accidentally splitting the actual contents
tmpColDelim = String.fromCharCode(11), // vertical tab character
tmpRowDelim = String.fromCharCode(0), // null character
// actual delimiter characters for CSV format
colDelim = ',',
rowDelim = '\r\n',
// Grab text from table into CSV formatted string
csv = $rows.map(function(i, row) {
var $row = $(row),
$cols = $row.find('td');
return $cols.map(function(j, col) {
var $col = $(col),
text = '="' + $col.text() + '"'; // to make dates interpret literally in excel
return text.replace(/"/g, '"'); // escape double quotes
}).get().join(tmpColDelim);
}).get().join(tmpRowDelim)
.split(tmpRowDelim).join(rowDelim)
.split(tmpColDelim).join(colDelim);
IE behaves differently than other browsers:
// IE9+ support - using iframe to set up file
// https://github.com/angular-ui/ui-grid/issues/2312#issuecomment-70348120
// note: if using IE10+, consider ieblob: https://github.com/mholt/PapaParse/issues/175#issuecomment-75597039
if (msieversion()) {
var frame = document.createElement('iframe');
document.body.appendChild(frame);
frame.contentWindow.document.open("text/html", "replace");
frame.contentWindow.document.write('sep=,\r\n' + csv);
frame.contentWindow.document.close();
frame.contentWindow.focus();
frame.contentWindow.document.execCommand('SaveAs', true, fileName);
document.body.removeChild(frame);
return true;
} else {
var uri = 'data:application/csv;charset=utf-8,' + encodeURIComponent(csv);
$(this).attr({
'download': fileName,
'href': uri,
'target': '_blank'
});
}
These are just snippets, see the full jsfiddle for details.
I modified the commented-out code references to work with my table - I thought the table-to-string bit would help you, if you want to do any of this client-side.

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>

Nested Key-Value lookups in php

I am trying to make a "stock" website for a class at school, and it's my first dive into php. Basically, the script pulls down a CSV file form a google docs spreadsheet, and (attempts) to put the values into an array for use later. I'd like to show the top 5 rising and falling stocks, but am having issues. Here's main section of the script:
<html>
<head>
<?php
#Global Variables
$rising = array();
$falling = array();
$stocks = array();
#End Global Variables
#Function to read data from the spreadsheet
function get_data($url){
$ch = curl_init();
$timeout = 5;
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
#Process data
function populateTicker(){
$document = "https://docs.google.com/spreadsheet/pub?hl=en_US&hl=en_US&key=0AtrtT_MC9_YFdHRDUGx0a2xveXNfOHJVdXJ6bVNkMFE&output=csv";
$data= get_data($document);
$lines = explode("\n", $data);
$val = "";
foreach($lines as $key => $value){
if($key != 0){
$stockInfo = explode(",", $value);
$perChange = $stockInfo[3];
$perChangeVal = "up ";
if($perChange < 0){
$perChangeVal = "down ";
$falling['$stockInfo[0]'] = $perChange;
}else{
$rising['$stockInfo[0]'] = $perChange;
}
$stocks['$stockInfo[0]'] = array("symb" => $stockInfo[0], "name" => $stockInfo[1], "price" => $stockInfo[2]);
$val = $val . "(" . $stockInfo [0] . ") " . $stockInfo [1] . " " . "\$" . $stockInfo [2] . " " . $perChangeVal . $perChange . "% today" . "\v \v \v \v | \v \v \v \v";
}
}
//asort($falling);
//arsort($rising);
return $val;
}
function getRising($index){
if($index <= count($rising)){
$keys = array_keys($rising);
$data = $stocks[$keys[$index]];
return "(" . $data['symb'] . ") " . $data['name'] . " " . "\$" . $data['price'];
}else{
return ".";
}
}
function getFalling($index){
if($index <= count($falling)){
$keys = array_keys($falling);
$data = $stocks[$keys[$index]];
return "(" . $data['symb'] . ") " . $data['name'] . " " . "\$" . $data['price'];
}else{
return ".";
}
}
?>
</head>
<body>
<DIV id='DEBUG'>
<?php
print_r($stocks);
print_r($rising);
print_r($falling);
?>
</DIV>
<center><b><u><font size="+2">Latest Prices</font><br /></u></b></center>
<DIV ID="TICKER" STYLE="border-top:2px solid #CCCCCC; border-bottom:2px solid #CCCCCC; overflow:hidden; width:100%" onmouseover="TICKER_PAUSED=true" onmouseout="TICKER_PAUSED=false">
<?php echo populateTicker(); ?>
</DIV>
<script type="text/javascript" src="webticker_lib.js" language="javascript"></script>
<div id='Top5'>
<br />
<center><b>This page does not update automatically! Please refresh the page to update the information!</b></center>
<br />
<center><b><u><font size="+2">Top 5's</font><br /></u></b></center>
<center>
<table border="1" cellpadding="5">
<tr>
<th>Top 5 Rising</th>
<th>Top 5 Falling</th>
</tr>
<tr>
<td><?php echo getRising(1); ?></td>
<td><?php echo getFalling(1); ?></td>
</tr>
<tr>
<td><?php echo getRising(2); ?></td>
<td><?php echo getFalling(2); ?></td>
</tr> <tr>
<td><?php echo getRising(3); ?></td>
<td><?php echo getFalling(3); ?></td>
</tr> <tr>
<td><?php echo getRising(4); ?></td>
<td><?php echo getFalling(4); ?></td>
</tr> <tr>
<td><?php echo getRising(5); ?></td>
<td><?php echo getFalling(5); ?></td>
</tr>
</table>
</center>
</div>
<br />
<center><b><u><font size="+2">All Stocks</font><br /></u></b></center>
<div id='All'>
<center>
<table border="1" cellpadding="5">
<tr>
<th>Symbol</th>
<th>Name</th>
<th>Price</th>
<th>High</th>
<th>Low</th>
<th>Percent Change</th>
</tr>
<?php
#Dynamic Table Creation
foreach($stocks as $key => $value){
echo '<tr>';
echo '<td>(' . $value['symb'] . ')</td>';
echo '<td>' . $value['name'] . '</td>';
echo '<td>' . $value['price'] . '</td>';
echo '<td></td>';
echo '<td></td>';
echo '<td>' . $vaule['perChange'] . '</td>';
echo '</tr>';
}
?>
</table>
</center>
</div>
</body>
<footer>
</footer>
</html>
But nothing gets assigned to the arrays. Any help would be appreciated.
UPDATE: I added the full source of the front page, index.php
UPDATE2: I figured it out. I come from java, and didn't fully understand how the scope of variables worked in php. A simple
<?php
global $rising, $falling, $stocks;
...
?>
did the trick
I don't know exactly about your code but I can show an example for presenting the nested arrays:
$arr = array('1' => array('1', '2'), '2');
function showNested($array)
{
foreach($array as $key => $value)
{
if(is_array($value))
{
echo $value;
showNested($array);
}
else
{
echo $value;
}
}
}
UPDATE
You used $stocks['$stockInfo[0]'] in your code. I think this kind of syntax would never do anything. Totally when you use a variable in a string, you should surround it by {}. And one thing else that I never tested it before, I don't think putting an array with an index in a string would help the PHP to understand what's the current data in [].

Categories