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.
Related
When I import XLS files, I would like to avoid the import of empty rows. I tried with several codes without success. Can anyone help me?
This is the code:
require('xls/php-excel-reader/excel_reader2.php');
require('xls/SpreadsheetReader.php');
require_once '_inc/_db.php';
$r = rand();
$mimes = ['application/vnd.ms-excel', 'text/xls', 'text/xlsx', 'application/vnd.oasis.opendocument.spreadsheet'];
if (in_array($_FILES["file"]["type"], $mimes)) {
$uploadFilePath = 'storage/' . basename($_FILES['file']['name']);
move_uploaded_file($_FILES['file']['tmp_name'], $uploadFilePath);
rename($uploadFilePath, "storage/" . $r . ".xls");
$uploadFilePath = "storage/" . $r . ".xls";
$Reader = new SpreadsheetReader($uploadFilePath);
$totalSheet = count($Reader->sheets());
$tot = 0;
/* For Loop for all sheets */
for ($i = 0; $i < $totalSheet; $i++) {
$Reader->ChangeSheet($i);
$tots = $totalSheet;
foreach ($Reader as $Row) {
$tot++;
$nrcontenitore = isset($Row[0]) ? $Row[0] : '';
$nrcontenitore = str_replace(".", "", $nrcontenitore);
$nrcontenitore = str_replace("-", "", $nrcontenitore);
$nrcontenitore = str_replace("_", "", $nrcontenitore);
$nrcontenitore = str_replace("/", "", $nrcontenitore);
$nrcontenitore = str_replace("\'", "", $nrcontenitore);
$nrcontenitore = preg_replace('/\s+/', '', $nrcontenitore);
$nrcontenitore = isset($Row[0]) ? $Row[0] : '';
$data = isset($Row[1]) ? $Row[1] : '';
$doc .= formatcontainernr(strtoupper($nrcontenitore)) . " | " . date("d/m/Y", strtotime($data)) . "\n";
$docarr .= formatcontainernr(strtoupper($nrcontenitore)) . " | " . date("d/m/Y", strtotime($data)) . "#\n";
}
}
}
I would like to import a XLS file with no empty rows.
try to add a checking if the row is empty
foreach ($reader as $row) {
if($row == null){
continue;
}
}
I am using XMLReader to import huge xml file by elements to MySQL database. Xml contains 1 547 772 tags (element) named 'RECORD'.
XML example
<?xml version="1.0" encoding="utf-8"?>
<RECORD><NAME>ДОШКІЛЬНИЙ НАВЧАЛЬНИЙ ЗАКЛАД №1 ЗАГАЛЬНОГО РОЗВИТКУ УЖГОРОДСЬКОЇ МІСЬКОЇ РАДИ ЗАКАРПАТСЬКОЇ ОБЛАСТІ</NAME><SHORT_NAME>ДНЗ №1</SHORT_NAME><EDRPOU>34888585</EDRPOU><ADDRESS>88000, Закарпатська обл., місто Ужгород, ВУЛИЦЯ М.ВОВЧКА, будинок 47, "А"</ADDRESS><BOSS>НАКОНЕЧНА ОЛЕНА АНАТОЛІЇВНА</BOSS><KVED>85.10 Дошкільна освіта</KVED><STAN>зареєстровано</STAN><FOUNDERS><FOUNDER>УПРАВЛІННЯ ОСВІТИ УЖГОРОДСЬКОЇ МІСЬКОЇ РАДИ, розмір внеску до статутного фонду - 0.00 грн.</FOUNDER>...</FOUNDERS></RECORD>...
For MySQL connection use
function connectBase(){
include __DIR__ . '/../../settings/sql.set.php';
$mysql = mysqli_connect($_sqlhost, $_sqluser, $_sqlpass, $_sqldb);
mysqli_query($mysql, "Set charset utf8");
mysqli_query($mysql, "Set character_set_client = utf8");
mysqli_query($mysql, "Set character_set_connection = utf8");
mysqli_query($mysql, "Set character_set_results = utf8");
mysqli_query($mysql, "Set collation_connection = utf8_general_ci");
return $mysql;
}
Main function for parsing
function XMLReaderToDB($setting = false)
{
$mysql = connectBase();
$dir = __DIR__ . '/../../tmp/';
$xmlURL = $dir . $setting['file'];
$xml = new XMLReader();
$xml->open($xmlURL);
$start_time = time();
$start = $setting['start'];
$limit = $setting['limit'];
$stop = $start + $limit;
$i = 0;
$count = 0;
$result = 1;
while($xml->read())
{
if ($xml->nodeType == XMLReader::ELEMENT && $xml->name == $setting['tag']) {
$item[] = "('items', '" . mysqli_real_escape_string($mysql, $xml->readOuterXML()) . "')";
}
if ($xml->nodeType == XMLReader::END_ELEMENT && $xml->name == $setting['tag']) {
$i++;
$count++;
if ($count >= 500) {
insertXMLtoDB($mysql, $item);
$item = array();
$count = 0;
}
}
if($i == $stop){
break;
}
}
$xml->close();
insertXMLtoDB($mysql, $item);
$mysql->close();
$end_time = time();
$time_elapsed_secs = $end_time - $start_time;
echo '<br/>Items: ' . $i . '<br/>';
echo 'Start: ' . date('H:i:s', $start_time) . '<br/>';
echo 'End: ' . date('H:i:s', $end_time) . '<br/>';
echo $time_elapsed_secs . ' sec. (' . ($time_elapsed_secs /60) . ' min.)';
die;
}
And for MySQL insert
function insertXMLtoDB($mysql, $data = false){
mysqli_query($mysql,"INSERT INTO _parse_tmp (parse_key, parse_value) VALUES " . implode(", ", $data));
$data = array();
// echo 'Success';
}
But, MySQL requests don't stop after 1 547 772 inserts and "while" continues to run. I notice if uncommenting echo 'Success'; in insertXMLtoDB function, "while" is stopping at 1 547 772 inserts and finishing correctly.
What is wrong in my functions?
I've never personally used XMLReader however, I'd assume you could try to add another condition to your statement such as while($xml->read() && $i != $stop) opposed to having it within your loop directly. Ah also just noticed after your usage of the function insertXMLtoDB you re-declare $data although you'll notice you set it to NULL every time your call the function, therefore setting it to an array is pointless.
I can't understand why the script doesn't work fine. That's why I decided to change it.
function XMLReaderToDB($setting = false)
{
$mysql = connectBase();
$dir = __DIR__ . '/../../tmp/';
$xmlURL = $dir . $setting['file'];
$xml = new XMLReader();
$xml->open($xmlURL);
$start_time = time();
$start = $setting['start'];
$limit = $setting['limit'];
$stop = $start + $limit;
$i = 0;
$count = 0;
while (($valid = $xml->read()) && $xml->name !== $setting['tag']) ;
while ($valid) {
$i++;
$count++;
$item[] = "('" . $setting['type'] . "', '" . mysqli_real_escape_string($mysql, $xml->readOuterXML()) . "')";
if ($count == 500) {
insertXMLtoDB($mysql, $item);
$item = array();
$count = 0;
}
$valid = $xml->next($setting['tag']);
}
$xml->close();
insertXMLtoDB($mysql, $item);
$mysql->close();
$end_time = time();
$time_elapsed_secs = $end_time - $start_time;
echo '<br/>Items: ' . $i . '<br/>';
echo 'Start: ' . date('H:i:s', $start_time) . '<br/>';
echo 'End: ' . date('H:i:s', $end_time) . '<br/>';
echo $time_elapsed_secs . ' sec. (' . ($time_elapsed_secs /60) . ' min.)';
return;
}
I have an add post form to add new post. I have taken post title as post_url or slug. I want unique post_url.
Here is what I have done so far -
$post_name = $this->input->post('post_title');
function clean($post_name) {
$name = trim($post_name);
$post_name = str_replace(' ', '-', $name);
return preg_replace('/[^A-Za-z0-9\-]/', '', $post_name);
}
$post_url = clean($post_name);
$query = mysql_query("select post_url from sa_posts where post_url like '" . $post_url . "%'");
while ($r = mysql_fetch_assoc($query)) {
$slugs[] = $r['post_url'];
if (mysql_num_rows($query) !== 0 && in_array($post_url, $slugs)) {
$max = 0;
while (in_array(($post_url . '-' . ++$max), $slugs)) ;
$post_url .= '-' . $max;
}
}
echo "Slug " . $post_url;
I am getting output as -
post-url
post-url-1
post-url-1-1
post-url-1-1-1
But I want output as -
post-url
post-url-1
post-url-2
post-url-3
What is a problem in my code?
Please help me.
Thanks.
function UniqueSlugGenerator($p){
include("conn.php");
$RowCou=0;
$slug = preg_replace('/[^a-z0-9]/', '-', strtolower(trim(strip_tags($p))));
$qq = mysqli_query($conn,"select Slug from ser_posts where Slug like '$slug%'") or die(mysqli_error($conn));
$RowCou = mysqli_num_rows($qq);
return ($RowCou > 0) ? $slug.'-'.(++$RowCou) : $slug;
}
Change your code in the following way
$post_url = clean($post_name);
$post_url1 = $post_url;
$query = mysql_query("select post_url from sa_posts where post_url like '" . $post_url . "%'");
while ($r = mysql_fetch_assoc($query)) {
$slugs[] = $r['post_url'];
if (mysql_num_rows($query) !== 0 && in_array($post_url, $slugs)) {
$max = 0;
$post_url = $post_url1;
while (in_array(($post_url . '-' . ++$max), $slugs)) ;
$post_url .= '-' . $max;
}
}
echo "Slug " . $post_url;
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";
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