foreach loop prevous data in export file - php

I have a export script that export items to a csv file. I want to export the additional images for each item on each product row in the csv file.
That part looks like this:
$img_query=tep_db_query("SELECT additional_images_id, products_id, popup_images
FROM " . TABLE_ADDITIONAL_IMAGES . "
WHERE products_id=" . $products['products_id'] ."");
if (!tep_db_num_rows($img_query)) {
$imageextra2 = " ";
} else {
$img_rows=tep_db_num_rows($img_query);
while ($img = tep_db_fetch_array($img_query)) {
$img2 = $img['popup_images'];
$pid = $img['products_id'];
$a = array($img2);
foreach($a as &$img){
}
foreach($a as $imageextra) {
$imageextra = "http://www.URL.com/images/". $img2.";";
$imageextra2 .= $imageextra;
}
} }
But when I export more than one product that have additional images the images from the line abowe follows to the next line in the csv file.
Heres an exampe of the result. Each item has one additional image:
Item-A;AdditionalImage-A.jpg;AdditionalImage-A2.jpg
Item-B;AdditionalImage-A.jpg;AdditionalImage-A2.jpg;AdditionalImage-B.jpg;AdditionalImage-B2.jpg
Item-C;AdditionalImage-A.jpg;AdditionalImage-A2.jpg;AdditionalImage-B.jpg;AdditionalImage-B2.jpg;AdditionalImage-C.jpg;AdditionalImage-C2.jpg
What can I do to get this working?
Cheers,
Fredrik
Edit
Below is the complete section of php that grab the info and generate the export file:
<?php
require('includes/application_top.php');
if (isset($_POST['create'])) {
if (isset($_POST['product']) && is_array($_POST['product'])) {
foreach ($_POST['product'] as $product_id) {
$products_query_raw = "select p.products_id, p.products_image, p.products_model, products_image_pop, p.products_price, p.products_quantity, p.products_tax_class_id, pd.products_name, pd.products_description from " . TABLE_PRODUCTS . " p, " . TABLE_PRODUCTS_DESCRIPTION . " pd where p.products_id = $product_id and pd.products_id = p.products_id and pd.language_id = $languages_id";
$products_query = tep_db_query($products_query_raw);
if ($products = tep_db_fetch_array($products_query)) {
//++++ QT Pro: End Changed Code
$products_attributes_query = tep_db_query("select count(*) as total from " . TABLE_PRODUCTS_OPTIONS . " popt, " . TABLE_PRODUCTS_ATTRIBUTES . " patrib where patrib.products_id='" . $products['products_id'] . "' and patrib.options_id = popt.products_options_id and popt.language_id = '" . (int)$languages_id . "'");
$products_attributes = tep_db_fetch_array($products_attributes_query);
if ($products_attributes['total'] > 0) {
//++++ QT Pro: Begin Changed code
$products_id = $products['products_id'];
require_once(DIR_WS_CLASSES . 'pad_single_radioset_print.php');
$class = 'pad_single_radioset';
$pad = new $class($products_id);
$attribs .= $pad->draw();
//++++ QT Pro: End Changed Code
}
$product_desc = (isset($_POST['strip_tags']) && ($_POST['strip_tags'] == '1'))
? strip_tags($products['products_description'],'<br>, <li>, </li>, <ul>, </ul>') //ORG
: $products['products_description'];
$tax_rate = 0;
$taxes_query_raw = "select tax_rate from " . TABLE_TAX_RATES . " where tax_class_id = " . $products['products_tax_class_id'];
$taxes_query = tep_db_query($taxes_query_raw);
while ($taxes = tep_db_fetch_array($taxes_query)) {
$tax_rate += $taxes['tax_rate'];
}
$tax = ($products['products_price'] * $tax_rate) / 100;
$stock = $products['products_quantity'];
$product_desc=preg_replace("/([[:space:]]{2,})/",' ',$product_desc);
// Categories - just show the sub-category
$categories_list = Array();
$categories_query_raw = "select cd.categories_name, cd.categories_id from " . TABLE_PRODUCTS_TO_CATEGORIES . " ptc, " . TABLE_CATEGORIES_DESCRIPTION . " cd where ptc.products_id = " . $products['products_id'] . " and cd.categories_id = ptc.categories_id and cd.language_id = $languages_id";
$categories_query = tep_db_query($categories_query_raw);
while ($categories = tep_db_fetch_array($categories_query)) {
$categories_list[] = $categories['categories_name'];
$categories_id = $categories['categories_id'];
}
$category_name = implode(' / ', $categories_list);
// Additional images
$img_query=tep_db_query("SELECT additional_images_id, products_id, popup_images
FROM " . TABLE_ADDITIONAL_IMAGES . "
WHERE products_id=" . $products['products_id'] ."");
if (!tep_db_num_rows($img_query)) {
$imageextra2 = "; ; ";
} else {
$img_rows=tep_db_num_rows($img_query);
while ($img = tep_db_fetch_array($img_query)) {
$img2 = $img['popup_images'];
$pid = $img['products_id'];
$a = array($img2);
$imageextra2 = " "; # This avoid letting the additional images from lines abowe follow.
foreach($a as $imageextra) {
$imageextra = "http://www.URL.com/images/". $img2.";";
$imageextra2 .= $imageextra;
}
}
}
$export .=
$products['products_model'].';'.
$products['products_name'].';'.
$product_price.';'.
$products['products_quantity'].';'.
$product_desc.';'.
$categories_id.';'.
$shipping_cost.';'.
'http://www.URL.com/images/'.basename($products['products_image_pop']).';'.
$imageextra2.
"\n";
}
}
if ($fp = #fopen($_SERVER['DOCUMENT_ROOT'] . '/feed/t-butik.csv', 'w')) {
$utf = iconv("windows-1252","ISO-8859-1",$export);
$out = 'variable_name='.$utf;
fwrite($fp, $utf);
fclose($fp);
$messageStack->add("Feed generates successfully!!!", 'success');
} else {
$messageStack->add("ERROR: Permissions error trying to write feed to disk.", 'error');
}
}
}
?>

There doesn't seem to be enough of the code to give you an absolute answer but my guess would be that the variable $imageextra2 is not being reset on each iteration.
When you change a product you should reset the variable thats holding the images, which I assume is $imageextra2
Change This
if (!tep_db_num_rows($img_query)) {
$imageextra2 = "; ; ";
} else {
$img_rows=tep_db_num_rows($img_query);
while ($img = tep_db_fetch_array($img_query)) {
$img2 = $img['popup_images'];
$pid = $img['products_id'];
$a = array($img2);
$imageextra2 = " "; # This avoid letting the additional images from lines abowe follow.
foreach($a as $imageextra) {
$imageextra = "http://www.URL.com/images/". $img2.";";
$imageextra2 .= $imageextra;
}
}
}
To This
$imageextra2 = " "; # resets images
if (tep_db_num_rows($img_query)) {
$img_rows=tep_db_num_rows($img_query);
while ($img = tep_db_fetch_array($img_query)) {
$img2 = $img['popup_images'];
$pid = $img['products_id'];
$a = array($img2);
foreach($a as $imageextra) {
$imageextra = "http://www.URL.com/images/". $img2.";";
$imageextra2 .= $imageextra;
}
}
}
Best Regards,
Jason

Related

How give colour to a cell in pdf using php?

I need to give color to a specific cell in pdf which is generated from my MySQL database, How to set the color to the specific value?
I have no clue about giving color to the specific value, I there any way help me out?
my pdf generate page is:
$fdate = date('Y-m-d H:i:s', strtotime($fromdate));
$tdate = date('Y-m-d H:i:s', strtotime( $todate));
/*$channelsCol = Channels::find()
->select(['channel_name'])
->where('DeviceRefID != :id',['id' => 0 ])
->orderBy('channel_no')
->all();*/
$channelscol = \Yii::$app->db
->createCommand("select channel_name from channels where deviceRefID !=0")
->queryAll();
$pdfpages = $this->getNoOfPdfs(count($channelscol));
$noOfPages = count($pdfpages[0]);
$collist=[];
$selectlist=[];
for($i=0; $i < $noOfPages;$i++)
{
$collist[$i] = 'Select SQL_BUFFER_RESULT "LogDateTime ",';
$selectlist[$i] = 'select LogDateTime,';
}
$count =0;
$counter=1;
for($i=0;$i<$noOfPages;$i++)
{
for($j=$pdfpages[0][$i];$j<$pdfpages[1][$i];$j++)
{
$collist[$i] = $collist[$i] . '"'.$channelscol[$j-1]['channel_name'] .'",';
$selectlist[$i] = $selectlist[$i] . 'Channel'.$j.'Value,';
$count = $count + 1;
}
}
for($i=0;$i <$noOfPages ;$i++)
{
$collist[$i] = rtrim($collist[$i],",");
$selectlist[$i] = rtrim($selectlist[$i],",");
}
//$path ="/var/www/devicesadmin/yii-app/web/devicelog/devicelog" . date("Y-m-d-H-i-s").".csv";
$logfilename =[];
$logfailure="";
for($i=0;$i < $noOfPages; $i++)
{
$logfilename[$i] = $pdfpages[2][$i] . date("Y-m-d-H-i-s") . mt_rand() . ".csv";
//$path ='D:/Raffi/ProjectsPhp/DevicesAdminProject/yii-app/web/devicelog//' . $logfilename[$i];
$path = "/var/www/devicesadmin/yii-app/web/devicelog/" . $logfilename[$i];
$export =' INTO OUTFILE "' . $path . '" FIELDS TERMINATED BY "," ENCLOSED BY \'"\' LINES TERMINATED BY \'\\n\' FOR UPDATE';
$whereclause = "where LogDatetime between '" . $fdate . "' and '" .$tdate ."'";
$finalsql = $collist[$i] . ' Union all ' .$selectlist[$i] .' From devicelog '. $whereclause . $export;
try {
Yii::$app->db->createCommand($finalsql)->execute();
//file_put_contents("D:\my.txt", $this->getHTML($path, $header));
//echo html($this->getHTML($path, $header));
//exit();
$pdf=new \PDF('P','mm','Legal');
$pdf->AliasNbPages();
//$pdf=new \PDF('L','mm','Legal',130);
$pdf->AddPage();
$pdf->SetFont('helvetica','',10);
$pdf->WriteHTML($this->getHTML($path));
$logfilename[$i] = "dl" . $pdfpages[2][$i] . date("Y-m-d-H-i-s").".pdf";
//$filename = "D:/Raffi/ProjectsPhp/DevicesAdminProject\yii-app\web\devicelog" . $logfilename[$i];
$filename = "/var/www/devicesadmin/yii-app/web/devicelog/" . $logfilename[$i];
$pdf->Output('F',$filename);
unset($pdf);
} catch(Exception $e) {
}
}
If a pdf is generated, I need to give red color to the values which are above 50. But I can't get the values and give color.

PHP/MySQL - Ordering a database table by year and month separately.

I'm trying to build a HTML table from a list of newsletters in a MySQL database.
It's currently ordered by descending order, and outputting as below:
https://jsfiddle.net/e8zrLjqu/
As you will see the years are in the right place, but the months of the newsletters need to be in ascending order, while keeping the years in descending order, so that each newsletter matches up with the table heading....like this example:
Do I somehow need to use DATE_FORMAT to separate the ordering? The date in the database is formatted like this: 2014-07-01
Php:
$category_data_fields = '`id`';
$category_where_conditions = '`publish` = \'y\' and `fund_id` = ' . $this_fund_id . ' and `category_status` = \'n\'';
$category_result = $db->selectByStrings($category_data_fields, '`category`', $category_where_conditions, '`position`');
$resource_data_fields = '`id`, `date`, `heading`, `file`';
$heading_investor_newsletter = $lang_row['name'] . ' Investor Newsletters';
$copy_investor_newsletter = $tab0 . $lang_row['investor_news_copy'] . $retn . $retn;
$note = $tab1 . $lang_row['investor_news_note'] . $retn . $retn;
if ($db->getNumRows($category_result) > 0) {
$cat_data = $db->getNextRow($category_result);
/*
* list selectable years
*/
$resource_where_conditions = '`publish` = \'y\' and `category_id` = ' . $cat_data['id'];
$date_result = $db->selectByStrings($resource_data_fields, '`resource`', $resource_where_conditions, '`date` desc');
$current_year = '';
$base_url_query = (_USE_SEO_URLS === true) ? $_SERVER['PHP_SELF'] . '?' : $_SERVER['REQUEST_URI'] . '&';
if ($req->isRequest ('year')) $url_year = $req->getRequest ('year');
if ($db->getNumRows($date_result) > 0) {
$copy_investor_newsletter .= $tab0 . '<table class="table table-bordered table-responsive"><tbody><thead><tr><th>January</th><th>Feburay</th><th>March</th><th>April</th><th>May</th><th>June</th><th>July</th><th>August</th><th>September</th><th>October</th><th>November</th><th>December</th></tr></thead>' . $retn;
while ($data = $db->getNextRow($date_result)) {
if (substr ($data['date'], 0, 4) != $current_year) {
$current_year = substr ($data['date'], 0, 4);
if (!isset ($latest_year)) $latest_year = $current_year;
if (!isset ($url_year)) {
$navsel = ' class="ActNav"';
$url_year = $current_year;
} elseif ($url_year == $current_year) {
$navsel = ' class="ActNav"';
$selected_year = $url_year;
} else $navsel = '';
$copy_investor_newsletter .= $tab1 . '<tr>';
// if ($url_year == $current_year) {
/*
* read and display all newsletters for selected year
*/
$resource_where_conditions = '`publish` = \'y\' and `category_id` = ' . $cat_data['id'] . ' and substr(`date`,1,4) = \'' . $current_year . '\'';
$resource_result = $db->selectByStrings($resource_data_fields, '`resource`', $resource_where_conditions, '`date` desc');
if ($db->getNumRows($resource_result) > 0) {
// $copy_investor_newsletter .= $retn . $tab2 . '<ul>' . $retn;
while ($data = $db->getNextRow($resource_result)) {
$copy_investor_newsletter .= $tab3 . '<td>' . $data['heading'] . '</td>' . $retn;
}
// $copy_investor_newsletter .= $tab2 . '</ul>' . $retn . $tab1;
}
// }
$copy_investor_newsletter .= '</tr>' . $retn;
}
}
$copy_investor_newsletter .= $tab0 . '</tbody></table>' . $retn . $retn;
}
}
}
Try:
... ORDER BY YEAR(`date`) DESC, MONTH(`date`) ASC
See also the documentation of YEAR and MONTH

OSCommerce price schedule inconsistent behaviour

Working on a problem with an "old" shop in OSCommerce. It's a multistore configuration which is tweaked by the previous owner. I have 2 similar products with a price schedule or quantity price break feature.
The problem is 1 of the 2 products is not reacting consistent when added to cart or showing the product page.
1st product: has a price schedule of >5, >10, >20 and >30, with prices from high to low.
2nd product: has the same schedule but is somehow shown the other way around: >30, >20, >10 and >5 with prices from low to high.
The weird thing is that the option sort_order does not exist in the price schedule table so the way that the quantity order is shown is random, but always from high to low or low to high.
The first product shows the correct price in the shopping cart, the second product always shows the highest price at any quantity, where the shopping cart should adjust the price according to the price schedule data.
Done so far without any luck:
Checked the price schedule configuration in backend
Checked product configuration in backend and rechecked in Database
Checked all related database tables
After discovering that the only difference between the products are: product name, product image and product_id, gave the product an product_id close to the working one. Also changed all the related database entry's
Make a copy of the correctly working product and add a price schedule as well.
Here is the code of the class which generates the price_schedule:
<?php
/*
$Id: price_schedule.php,v 1.0 2004/08/23 22:50:52 rmh Exp $
osCommerce, Open Source E-Commerce Solutions
http://www.oscommerce.com
Copyright (c) 2003 osCommerce
Released under the GNU General Public License
*/
/*
price_schedule.php - module to support customer classes with quantity pricing
Originally Created 2003, Beezle Software based on some code mods by WasaLab Oy (Thanks!)
Modified by Ryan Hobbs (hobbzilla)
*/
class PriceFormatter {
var $hiPrice;
var $lowPrice;
var $quantity;
var $hasQuantityPrice;
var $hasSpecialPrice;
var $qtyPriceBreaks;
function PriceFormatter($prices=NULL) {
$this->productsID = -1;
$this->hasQuantityPrice=false;
$this->hasSpecialPrice=false;
$this->hiPrice=-1;
$this->lowPrice=-1;
$this->thePrice = -1;
$this->specialPrice = -1;
$this->qtyBlocks = 1;
$this->qtyPriceBreaks = 0;
if($prices) {
$this->parse($prices);
}
}
function encode() {
$str = $this->productsID . ":"
. (($this->hasQuantityPrice == true) ? "1" : "0") . ":"
. (($this->hasSpecialPrice == true) ? "1" : "0") . ":"
. $this->quantity[1] . ":"
. $this->quantity[2] . ":"
. $this->quantity[3] . ":"
. $this->quantity[4] . ":"
. $this->price[1] . ":"
. $this->price[2] . ":"
. $this->price[3] . ":"
. $this->price[4] . ":"
. $this->thePrice . ":"
. $this->specialPrice . ":"
. $this->qtyBlocks . ":"
. $this->taxClass;
return $str;
}
function decode($str) {
list($this->productsID,
$this->hasQuantityPrice,
$this->hasSpecialPrice,
$this->quantity[1],
$this->quantity[2],
$this->quantity[3],
$this->quantity[4],
$this->price[1],
$this->price[2],
$this->price[3],
$this->price[4],
$this->thePrice,
$this->specialPrice,
$this->qtyBlocks,
$this->taxClass) = explode(":", $str);
$this->hasQuantityPrice = (($this->hasQuantityPrice == 1) ? true : false);
$this->hasSpecialPrice = (($this->hasSpecialPrice == 1) ? true : false);
}
function parse($prices) {
global $customer_group_id, $customer_group_type, $customer_group_discount;
if (!tep_not_null($customer_group_id)) {
$customer_group_id = VISITOR_PRICING_GROUP;
$check_group_query = tep_db_query("select customers_groups_type, customers_groups_discount from " . TABLE_CUSTOMERS_GROUPS . " where customers_groups_id = '" . (int)$customer_group_id . "'");
$check_group = tep_db_fetch_array($check_group_query);
$customer_group_type = $check_group['customers_groups_type'];
$customer_group_discount = $check_group['customers_groups_discount'];
}
$this->productsID = $prices['products_id'];
$this->hasQuantityPrice=false;
$this->hasSpecialPrice=false;
// if ($customer_group_type != '1') {
// $price_schedule_query = tep_db_query("select products_groups_price, products_groups_price_qty FROM " . TABLE_PRODUCTS_PRICE_SCHEDULES . " WHERE products_id = '" . $prices['products_id'] . "' and customers_groups_id = '" . (int)$customer_group_id . "' and stores_id = '" . STORES_ID . "'");
$price_schedule_query = tep_db_query("select products_groups_price, products_groups_price_qty FROM " . TABLE_PRODUCTS_PRICE_SCHEDULES . " WHERE products_id = '" . $prices['products_id'] . "' and stores_id = '" . STORES_ID . "'");
$this->qtyPriceBreaks = tep_db_num_rows($price_schedule_query);
$this->thePrice = $prices['products_price'];
$this->specialPrice = $prices['specials_new_products_price'];
// } else {
// $this->qtyPriceBreaks = 0;
// $this->thePrice = $prices['products_price'] * (100 - $customer_group_discount)/100;
// $this->specialPrice = $prices['specials_new_products_price'];
// if ($this->thePrice < $this->specialPrice) $this->specialPrice = "";
// }
$this->hiPrice = $this->thePrice;
$this->lowPrice = $this->thePrice;
$this->hasSpecialPrice = tep_not_null($this->specialPrice);
$this->qtyBlocks = $prices['products_qty_blocks'];
$this->taxClass=$prices['products_tax_class_id'];
$n = 0;
if ($this->qtyPriceBreaks > 0 ) {
while ($price_schedule = tep_db_fetch_array($price_schedule_query)) {
$this->price[$n]=$price_schedule['products_groups_price'];
$this->quantity[$n]=$price_schedule['products_groups_price_qty'];
if ($this->quantity[$n] == '1') {
$this->thePrice = $this->price[$n];
$this->hiPrice = $this->thePrice;
$this->lowPrice = $this->thePrice;
} else {
$this->hasQuantityPrice = true;
}
$n += 1;
}
}
for($i=0; $i<$this->qtyPriceBreaks; $i++) {
if ($this->hasSpecialPrice == true) {
$this->hiPrice = $this->specialPrice;
if ($this->price[$i] > $this->specialPrice) {
$this->price[$i] = $this->specialPrice;
}
}
if ($this->hasQuantityPrice == true) {
if ($this->price[$i] > $this->hiPrice) {
$this->hiPrice = $this->price[$i];
}
if ($this->price[$i] < $this->lowPrice) {
$this->lowPrice = $this->price[$i];
}
}
}
}
function loadProduct($product_id, $language_id=1)
{
$sql="select pd.products_name, p.products_model, p.products_image, p.products_leadtime, p.products_id, p.manufacturers_id, p.products_price, p.products_weight, p.products_unit, p.products_qty_blocks, p.products_tax_class_id, p.distributors_id, IF(s.status = '1' AND s.stores_id = '" . STORES_ID . "', s.specials_new_products_price, NULL) as specials_new_products_price, IF(s.status = '1' AND s.stores_id = '" . STORES_ID . "', s.specials_new_products_price, p.products_price) as final_price from " . TABLE_PRODUCTS_TO_CATEGORIES . " p2c, ((" . TABLE_PRODUCTS . " p left join " . TABLE_MANUFACTURERS . " m on p.manufacturers_id = m.manufacturers_id, " . TABLE_PRODUCTS_DESCRIPTION . " pd) left join " . TABLE_SPECIALS . " s on p.products_id = s.products_id and s.stores_id = '" . STORES_ID . "') INNER JOIN " . TABLE_PRODUCTS_TO_STORES . " p2s ON p.products_id = p2s.products_id where p2s.stores_id = '" . STORES_ID . "' AND p.products_status = '1' and p.products_id = '" . (int)$product_id . "' and pd.products_id = '" . (int)$product_id . "' and pd.language_id = '". (int)$language_id ."'";
$product_info_query = tep_db_query($sql);
$product_info = tep_db_fetch_array($product_info_query);
$this->parse($product_info);
return $product_info;
}
function computePrice($qty) {
$qty = $this->adjustQty($qty);
$price = $this->thePrice;
if ($this->hasSpecialPrice == true) {
$price = $this->specialPrice;
}
if ($this->hasQuantityPrice == true) {
for ($i=0; $i<$this->qtyPriceBreaks; $i++) {
if (($this->quantity[$i] > 0) && ($qty >= $this->quantity[$i])) {
$price = $this->price[$i];
}
}
}
return $price;
}
// Force QTY_BLOCKS granularity
function adjustQty($qty) {
$qb = $this->getQtyBlocks();
if ($qty < 1) {
$qty = 0;
return $qty;
}
if ($qb >= 1) {
if ($qty < $qb) {
$qty = $qb;
}
if (($qty % $qb) != 0) {
$qty += ($qb - ($qty % $qb));
}
}
return $qty;
}
function getQtyBlocks() {
return $this->qtyBlocks;
}
function getPrice() {
return $this->thePrice;
}
function getLowPrice() {
return $this->lowPrice;
}
function getHiPrice() {
return $this->hiPrice;
}
function hasSpecialPrice() {
return $this->hasSpecialPrice;
}
function hasQuantityPrice() {
return $this->hasQuantityPrice;
}
function getPriceString($style='productPriceInBox') {
global $currencies, $customer_id;
// If you want to change the format of the price/quantity table
// displayed on the product information page, here is where you do it.
if (($this->hasSpecialPrice == true) && ($this->hasQuantityPrice == false)) {
$lc_text = ' <s>' . $currencies->display_price($this->thePrice, tep_get_tax_rate($this->taxClass)) . '</s> <span class="productSpecialPrice">' . $currencies->display_price($this->specialPrice, tep_get_tax_rate($this->taxClass)) . '</span>';
}
if($this->hasQuantityPrice == true) {
$lc_text = '<table align="top" border="0" cellspacing="0" cellpadding="0"><tr><td align="center" colspan="2"><b>' . ($this->hasSpecialPrice == true ? '<s>' . $currencies->display_price($this->thePrice, tep_get_tax_rate($this->taxClass)) . '</s> <span class="productSpecialPrice">' . $currencies->display_price($this->specialPrice, tep_get_tax_rate($this->taxClass)) . '</span> ' : 'vanaf ' . $currencies->display_price($this->lowPrice, tep_get_tax_rate($this->taxClass)) ) . '</b></td></tr>';
for($i=0; $i<=$this->qtyPriceBreaks; $i++) {
if(($this->quantity[$i] > 0) && ($this->price[$i] > $this->specialPrice)) {
$lc_text .= '<tr><td class='.$style.' align="right">> ' . $this->quantity[$i] . ' </td><td class='.$style.'>' . $currencies->display_price($this->price[$i], tep_get_tax_rate($this->taxClass)) . '</td></tr>';
}
}
$lc_text .= '</table>';
} else {
if ($this->hasSpecialPrice == true) {
$lc_text = ' <s>' . $currencies->display_price($this->thePrice, tep_get_tax_rate($this->taxClass)) . '</s> <span class="productSpecialPrice">' . $currencies->display_price($this->specialPrice, tep_get_tax_rate($this->taxClass)) . '</span>';
} else {
$lc_text = ' ' . $currencies->display_price($this->thePrice, tep_get_tax_rate($this->taxClass)) . '';
}
}
// if (VISITOR_PRICING_GROUP < '0' && !tep_session_is_registered('customer_id')) {
// return '';
// } else {
return $lc_text;
// }
}
function getPriceStringShort() {
global $currencies, $customer_id;
if (($this->hasSpecialPrice == true) && ($this->hasQuantityPrice == false)) {
$lc_text = '<div class="priceold">' . $currencies->display_price($this->thePrice, tep_get_tax_rate($this->taxClass)) . '</div><div class="pricenew">' . $currencies->display_price($this->specialPrice, tep_get_tax_rate($this->taxClass)) . '</div>';
} elseif ($this->hasQuantityPrice == true) {
$lc_text = '<div class="vanaf">vanaf</div><div class="price">' . $currencies->display_price($this->lowPrice, tep_get_tax_rate($this->taxClass)) . ' </div>';
} else {
$lc_text = '<div class="price">' . $currencies->display_price($this->thePrice, tep_get_tax_rate($this->taxClass)) . '</div>';
}
// if (VISITOR_PRICING_GROUP < '0' && !tep_session_is_registered('customer_id')) {
// return TEXT_LOGIN_TO_SEE_PRICES;
// } else {
return $lc_text;
// }
}
}
?>
I'm not experienced enough to decipher the class and find strange things, if you need more info, do not hesitate to ask.
Any help would be apreciated.
As I understand your question, you would like the product prices to be ordered consistently. I'm aware of the addons you mention but I'm not very familiar with them. That being said you can try to change this line...
$price_schedule_query = tep_db_query("select products_groups_price, products_groups_price_qty FROM " . TABLE_PRODUCTS_PRICE_SCHEDULES . " WHERE products_id = '" . $prices['products_id'] . "' and stores_id = '" . STORES_ID . "'");
to
$price_schedule_query = tep_db_query("select products_groups_price, products_groups_price_qty FROM " . TABLE_PRODUCTS_PRICE_SCHEDULES . " WHERE products_id = '" . $prices['products_id'] . "' and stores_id = '" . STORES_ID . "'" . " ORDER BY products_groups_price ASC");
As I said, I'm not familiar with exactly how the addons you mentioned work but I'd start by adding ordering to the mysql query. This approach has worked for me on numerous occasions with various addons.

How To Change Numbers Based On Results

I have a follow up question on something I got help with here the other day (No Table Three Column Category Layout).
The script is as follows:
$res = mysql_query($query);
$system->check_mysql($res, $query, __LINE__, __FILE__);
$parent_node = mysql_fetch_assoc($res);
$id = (isset($parent_node['cat_id'])) ? $parent_node['cat_id'] : $id;
$catalist = '';
if ($parent_node['left_id'] != 1)
{
$children = $catscontrol->get_children_list($parent_node['left_id'], $parent_node['right_id']);
$childarray = array($id);
foreach ($children as $k => $v)
{
$childarray[] = $v['cat_id'];
}
$catalist = '(';
$catalist .= implode(',', $childarray);
$catalist .= ')';
$all_items = false;
}
$NOW = time();
/*
specified category number
look into table - and if we don't have such category - redirect to full list
*/
$query = "SELECT * FROM " . $DBPrefix . "categories WHERE cat_id = " . $id;
$result = mysql_query($query);
$system->check_mysql($result, $query, __LINE__, __FILE__);
$category = mysql_fetch_assoc($result);
if (mysql_num_rows($result) == 0)
{
// redirect to global categories list
header ('location: browse.php?id=0');
exit;
}
else
{
// Retrieve the translated category name
$par_id = $category['parent_id'];
$TPL_categories_string = '';
$crumbs = $catscontrol->get_bread_crumbs($category['left_id'], $category['right_id']);
for ($i = 0; $i < count($crumbs); $i++)
{
if ($crumbs[$i]['cat_id'] > 0)
{
if ($i > 0)
{
$TPL_categories_string .= ' > ';
}
$TPL_categories_string .= '' . $category_names[$crumbs[$i]['cat_id']] . '';
}
}
// get list of subcategories of this category
$subcat_count = 0;
$query = "SELECT * FROM " . $DBPrefix . "categories WHERE parent_id = " . $id . " ORDER BY cat_name";
$result = mysql_query($query);
$system->check_mysql($result, $query, __LINE__, __FILE__);
$need_to_continue = 1;
$cycle = 1;
$column = 1;
$TPL_main_value = '';
while ($row = mysql_fetch_array($result))
{
++$subcat_count;
if ($cycle == 1)
{
$TPL_main_value .= '<div class="col'.$column.'"><ul>' . "\n";
}
$sub_counter = $row['sub_counter'];
$cat_counter = $row['counter'];
if ($sub_counter != 0)
{
$count_string = ' (' . $sub_counter . ')';
}
else
{
if ($cat_counter != 0)
{
$count_string = ' (' . $cat_counter . ')';
}
else
{
$count_string = '';
}
}
if ($row['cat_colour'] != '')
{
$BG = 'bgcolor=' . $row['cat_colour'];
}
else
{
$BG = '';
}
// Retrieve the translated category name
$row['cat_name'] = $category_names[$row['cat_id']];
$catimage = (!empty($row['cat_image'])) ? '<img src="' . $row['cat_image'] . '" border=0>' : '';
$TPL_main_value .= "\t" . '<li>' . $catimage . '' . $row['cat_name'] . $count_string . '</li>' . "\n";
++$cycle;
if ($cycle == 7) // <---- here
{
$cycle = 1;
$TPL_main_value .= '</ul></div>' . "\n";
++$column;
}
}
if ($cycle >= 2 && $cycle <= 6) // <---- here minus 1
{
while ($cycle < 7) // <---- and here
{
$TPL_main_value .= ' <p> </p>' . "\n";
++$cycle;
}
$TPL_main_value .= '</ul></div>'.$number.'
' . "\n";
}
I was needing to divide the resulting links into three columns to fit my html layout.
We accomplished this by changing the numbers in the code marked with "// <---- here".
Because the amount of links returned could be different each time, I am trying to figure out how to change those numbers on the fly. I tried using
$number_a = mysql_num_rows($result);
$number_b = $number_a / 3;
$number_b = ceil($number_b);
$number_c = $number_b - 1;
and then replacing the numbers with $number_b or $number_c but that doesn't work. Any ideas?
As mentioned before, you can use the mod (%) function to do that.
Basically what it does is to get the remainder after division. So, if you say 11 % 3, you will get 2 since that is the remainder after division. You can then make use of this to check when a number is divisible by 3 (the remainder will be zero), and insert an end </div> in your code.
Here is a simplified example on how to use it to insert a newline after every 3 columns:
$cycle = 1;
$arr = range (1, 20);
$len = sizeof ($arr);
for ( ; $cycle <= $len; $cycle++)
{
echo "{$arr[$cycle - 1]} ";
if ($cycle % 3 == 0)
{
echo "\n";
}
}
echo "\n\n";

Undefined offset: 0 (Oscommerce bm.categories.php)

I have an issue with a file in oscommerce. In a customized bm_categories.php file I get a error:
Notice: Undefined offset: 0 in xxx\includes\modules\boxes\bm_categories.php on line 52
Here is the code.
I have marked Line 52 with : //THIS IS LINE 52//
I really hope someone can give me a hint.
Here is the code:
<?php
/*
$Id$
osCommerce, Open Source E-Commerce Solutions
http://www.oscommerce.com
Copyright (c) 2010 osCommerce
Released under the GNU General Public License
Modfied by Kevin Neufeld
Date: Novemeber 16, 2010
Released as contributions: Decenber 9th, 2010
*/
class bm_categories {
var $code = 'bm_categories';
var $group = 'boxes';
var $title;
var $description;
var $sort_order;
var $enabled = false;
function bm_categories() {
$this->title = MODULE_BOXES_CATEGORIES_TITLE;
$this->description = MODULE_BOXES_CATEGORIES_DESCRIPTION;
if ( defined('MODULE_BOXES_CATEGORIES_STATUS') ) {
$this->sort_order = MODULE_BOXES_CATEGORIES_SORT_ORDER;
$this->enabled = (MODULE_BOXES_CATEGORIES_STATUS == 'True');
$this->group = ((MODULE_BOXES_CATEGORIES_CONTENT_PLACEMENT == 'Left Column') ? 'boxes_column_left' : 'boxes_column_right');
}
}
function tep_show_category($counter) {
global $tree, $categories_string, $cPath_array, $pCounter; //added $pCounter
//additional Variables
//$pCounter is also globally defined and initialized in getData() and gets changed at the end of this function
$nCounter = $tree[$counter]['next_id'];
//Get item Levels
if($pCounter == 0){
$pLevel = 0;
}else{
$pLevel = $tree[$pCounter]['level'];
}
$cLevel = $tree[$counter]['level'];
//<---- THIS IS LINE 52 ------>//
$nLevel = $tree[$nCounter]['level'];
//Start of UnsortedList <ul> if Category level > 0
if($cLevel > 0){
if($cLevel != $pLevel){
$categories_string .= '<ul class="level ' . $cLevel . '">';
}
}
//Start of ListItem <li> and determines if List Item is Current
if (isset($cPath_array) && in_array($counter, $cPath_array)) {
if($cLevel == 0){
$categories_string .= '<li id="current" class=" active item'.$counter.'"><a href="';
}else{
$categories_string .= '<li class="item'.$counter.'"><a href="';
}
}else{
$categories_string .= '<li class="item'.$counter.'"><a href="';
}
//Gets and inserts URL path for link
if ($tree[$counter]['parent'] == 0) {
$cPath_new = 'cPath=' . $counter;
} else {
$cPath_new = 'cPath=' . $tree[$counter]['path'];
}
$categories_string .= tep_href_link(FILENAME_DEFAULT, $cPath_new) . '">';
//Gets CatgoryCounts if Set in Admin -- Seperator is also located here
if (SHOW_COUNTS == 'true') {
$products_in_category = tep_count_products_in_category($counter);
if ($products_in_category > 0) {
$showCount_string = '<span class="countSeperator"> ยป </span><span class="showCounts">[' . $products_in_category . ']</span>';
}
}
//Start of Span <span> around Category Name
if (isset($cPath_array) && in_array($counter, $cPath_array)) {
$categories_string .= '<span class="itemParentName">' . $tree[$counter]['name'] . '</span></a>';
} else {
$categories_string .= '<span class="itemName">'. $tree[$counter]['name'] . '</span></a></li>';
}
//This is used to determin the level and place the correct number of closing tags
if($cLevel > 0){
if ($cLevel > $nLevel){
$j = abs($cLevel - $nLevel);
$categories_string .= str_repeat('</ul></li>', $j);
}elseif ($nCounter == false){
$categories_string .= str_repeat('</ul></li>', $tree[$counter]['level']);
}
}
$pCounter = $counter;
if ($tree[$counter]['next_id'] != false) {
$this->tep_show_category($tree[$counter]['next_id']);
}
}
function getData() {
global $categories_string, $tree, $languages_id, $cPath, $cPath_array, $pCounter; //added $pCounter
$pCounter = 0; //initialize $pCounter
$categories_string = '';
$tree = array();
$categories_query = tep_db_query("select c.categories_id, cd.categories_name, c.parent_id from " . TABLE_CATEGORIES . " c, " . TABLE_CATEGORIES_DESCRIPTION . " cd where c.parent_id = '0' and c.categories_status = 1 and c.categories_id = cd.categories_id and cd.language_id='" . (int)$languages_id ."' order by sort_order, cd.categories_name");
while ($categories = tep_db_fetch_array($categories_query)) {
$tree[$categories['categories_id']] = array('name' => $categories['categories_name'],
'parent' => $categories['parent_id'],
'level' => 0,
'path' => $categories['categories_id'],
'next_id' => false);
if (isset($parent_id)) {
$tree[$parent_id]['next_id'] = $categories['categories_id'];
}
$parent_id = $categories['categories_id'];
if (!isset($first_element)) {
$first_element = $categories['categories_id'];
}
}
if (tep_not_null($cPath)) {
$new_path = '';
reset($cPath_array);
while (list($key, $value) = each($cPath_array)) {
unset($parent_id);
unset($first_id);
$categories_query = tep_db_query("select c.categories_id, cd.categories_name, c.parent_id from " . TABLE_CATEGORIES . " c, " . TABLE_CATEGORIES_DESCRIPTION . " cd where c.parent_id = '" . (int)$value . "' and c.categories_status = 1 and c.categories_id = cd.categories_id and cd.language_id='" . (int)$languages_id ."' order by sort_order, cd.categories_name");
if (tep_db_num_rows($categories_query)) {
$new_path .= $value;
while ($row = tep_db_fetch_array($categories_query)) {
$tree[$row['categories_id']] = array('name' => ''.$row['categories_name'],
'parent' => $row['parent_id'],
'level' => $key+1,
'path' => $new_path . '_' . $row['categories_id'],
'next_id' => false);
if (isset($parent_id)) {
$tree[$parent_id]['next_id'] = $row['categories_id'];
}
$parent_id = $row['categories_id'];
if (!isset($first_id)) {
$first_id = $row['categories_id'];
}
$last_id = $row['categories_id'];
}
$tree[$last_id]['next_id'] = $tree[$value]['next_id'];
$tree[$value]['next_id'] = $first_id;
$new_path .= '_';
} else {
break;
}
}
}
$this->tep_show_category($first_element);
$data = '<div id="categoryBoxContainer" class="ui-widget infoBoxContainer">' .
' <div class="ui-widget-header infoBoxHeading">' . MODULE_BOXES_CATEGORIES_BOX_TITLE . '</div>' .
' <div class="ui-widget-content infoBoxContents" style="background-color:#f5f5f5; border:none;"><ul class="menu">' . $categories_string . '</ul></div>' .
'</div>';
return $data;
}
function execute() {
global $SID, $oscTemplate;
if ((USE_CACHE == 'true') && empty($SID)) {
$output = tep_cache_categories_box();
} else {
$output = $this->getData();
}
$oscTemplate->addBlock($output, $this->group);
}
function isEnabled() {
return $this->enabled;
}
function check() {
return defined('MODULE_BOXES_CATEGORIES_STATUS');
}
function install() {
tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Enable Categories Module', 'MODULE_BOXES_CATEGORIES_STATUS', 'True', 'Do you want to add the module to your shop?', '6', '1', 'tep_cfg_select_option(array(\'True\', \'False\'), ', now())");
tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Content Placement', 'MODULE_BOXES_CATEGORIES_CONTENT_PLACEMENT', 'Left Column', 'Should the module be loaded in the left or right column?', '6', '1', 'tep_cfg_select_option(array(\'Left Column\', \'Right Column\'), ', now())");
tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Sort Order', 'MODULE_BOXES_CATEGORIES_SORT_ORDER', '0', 'Sort order of display. Lowest is displayed first.', '6', '0', now())");
}
function remove() {
tep_db_query("delete from " . TABLE_CONFIGURATION . " where configuration_key in ('" . implode("', '", $this->keys()) . "')");
}
function keys() {
return array('MODULE_BOXES_CATEGORIES_STATUS', 'MODULE_BOXES_CATEGORIES_CONTENT_PLACEMENT', 'MODULE_BOXES_CATEGORIES_SORT_ORDER');
}
}
?>
Do this. if $tree has index 0 then get its value else set it to empty string or whatever you want
$nLevel = isset($tree[$nCounter]['level']) ? $tree[$nCounter]['level'] : '';
It means, that your array has no key with the value 0. Check the $tree array:
var_dump( $tree );
and see what's inside there.
Seems, that:
$nCounter = $tree[$counter]['next_id'];
has no value in it; might id be, that there is no next_id ? If so, then check with isset before posting it:
$nLevel = (isset($tree[$nCounter]['level']) ? $tree[$nCounter]['level'] : '');
or add the same check when setting nCounter:
$nCounter = (isset($tree[$counter]['next_id']) ? $tree[$counter]['next_id'] : 0);

Categories