php report is very slow and crashes in firefox - php

I have a report that runs and returns 366 records, each containing a thumbnail that is 104 x 80 px. The issue is that the report runs very slowley even though I increased the memory size.
ini_set('memory_limit', '128M');
ini_set('max_execution_time','600');
After writing the SQL query I generate the table items here
generate_table_items($query_all_items);
This then runs through and checks for the image in the columns
function generate_table_items($query){
$columns = array();
$resultset = array();
$scriptname = array();
$scriptname[0] = "/reports/all_items.php";
$scriptname[1] = "/reports/all_items_by_value.php";
$columncount = 0;
$rowcost = 0;
$rowsale = 0;
while ($row = mssql_fetch_assoc($query)) {
if (empty($columns)) {
$columns = array_keys($row);
echo '<tr><th scope="col" >'.implode('</th><th scope="col" >',get_column_name($columns)).'</th></tr>';
$columncount = sizeof(array_keys($row));
}
$resultset[] = $row;
echo '<tr><td>'.implode('</td><td>',report_image_check($row)).'</td></tr>';
if(in_array($_SERVER['SCRIPT_NAME'],$scriptname)){
$colspan = (count($columns)-2);
echo "<tr><th scope='row'>Documents</th><td colspan='$colspan' >";
$PKID = $row['ID'];
if($row['SumOfTotalCost'] || $row['SumOfSalePrice']){
$rowcost += $row['SumOfTotalCost'];
$rowsale += $row['SumOfSalePrice'];
$get_total = true;
}
$query_docs = mssql_query("select documents.* from dbo.documents where documents.Antiquities_id = $PKID") or die ('get docs query failed ' . mssql_get_last_message());
while($row_docs = mssql_fetch_assoc($query_docs)){
$document = "../documents/" . $row_docs['document'];
echo "<a href='$document' title='opens in a new window' target='_blank' >" . $row_docs['document'] . "</a> | ";
} // End while (list docs)
mssql_free_result($query_docs);
echo "</td></tr>";
myflush();
} // End if all items and all items by value report
} // End While
echo '<tr>';
for($i=0;$i < $columncount-4;$i++){
echo '<td> </td>';
}
echo '<td>Total Cost '. $rowcost.'</td>';
echo '<td>Total Sale '. $rowsale.'</td>';
echo '<td>Total Calculated Difference '. ($rowsale-$rowcost).'</td></tr>';
} // End function
function get_column_name($columns){
$newcol = array();
$scriptname = array();
$scriptname[0] = "/reports/all_items.php";
$scriptname[1] = "/reports/all_items_by_value.php";
$thecount = 0;
foreach($columns as $col) {
if($thecount == 1 && in_array($_SERVER['SCRIPT_NAME'],$scriptname)) {
// Don't list the PK
} else {
$newcol[] = '<img id="'.$col.'" src="../images/icons/arrow_down.png" alt="click to sort by" onclick="sortby(\''.$col.'\');" />' . $col;
}
$thecount++;
}
/*if(in_array($_SERVER['SCRIPT_NAME'],$scriptname)){
$newcol[] = "documents";
}*/
return $newcol;
}
function report_image_check($row){
global $base_url, $uploaded_images_folder;
$newrow = array();
$imageext = array();
$imageext[0] = ".jpg";
$imageext[1] = ".png";
$imageext[2] = ".gif";
$imageext[3] = ".tiff";
$scriptname = array();
$scriptname[0] = "/reports/all_items.php";
$scriptname[1] = "/reports/all_items_by_value.php";
$PKID = 0;
$thecount = 0;
foreach($row as $rn) {
if(in_array(strtolower(substr($rn,-4)),$imageext)){
$small_img_ext = substr($rn,-4);
$small_img = substr($rn,0,strripos($rn,"."));
$small_img = $small_img . '_140_105' . $small_img_ext;
$newrow[] = '<a href="' . $base_url . $uploaded_images_folder . '/' . $small_img . '" title="click to zoom on image" target="_blank" ><img src="' . $base_url . $uploaded_images_folder . '/' . $rn . '" alt="" width="50px" height="50px" /></a>';
} elseif($thecount == 1 && in_array($_SERVER['SCRIPT_NAME'],$scriptname)) {
$PKID = $rn;
} elseif($thecount == 2 && in_array($_SERVER['SCRIPT_NAME'],$scriptname)) {
$newrow[] = "<a href='../index.php?template=10&PKID=$PKID' target='_blank' >$PKID (click to view)</a>";
} else {
$newrow[] = $rn;
}
$thecount++;
myflush();
}
/*if (in_array($_SERVER['SCRIPT_NAME'],$scriptname)) {
$newrow[] = "<a href='#&PKID=$PKID' target='_blank' >Documents (click to view)</a>";
}*/
return $newrow;
} // End function
//// Flushing function
function myflush(){
ob_implicit_flush();
ignore_user_abort();
}
Can anyone see an issue with this code or see why it would take so long or why it crashes firefox? Would printing to pdf function work better?

It'll take a long time because you're nesting SQL queries... executing a second SQL query for every result that has been returned by the first query.... Doing a single query with a JOIN should help performance significantly.
Printing to PDF would almost certainly be slower: you'd eithe rneed a lot of code to position everything correctly in the report yourself, or to use one of the libraries that can take HTML and render it to a PDF (as you're already generating HTML anyway at the moment, this would be additional processing)

Related

conditional statement does not work even if the statement returns true for image captions

I am trying to write a conditional if statement to get image caption if number of images match number of captions in the db row
code does work without if statement but fails to execute even if the condition returns true.
php
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$individual_files = explode("|", $row["images_names"]);
$individual_text = explode("_", $row["image_text"]);
for ($file_number = 0; $file_number < sizeof($individual_files) - 1; $file_number++) {
if( count($individual_files) == count($individual_text)) {
echo "<li>";
echo "<img src='Blog-Albums/" . $row["sno"] . "/" . $individual_files[$file_number] . "' alt='gallery image'/>";
echo "<div class='slider-caption'><p style='color:#ffffff'>this is sample file</p></div>";
echo "</li>";
} elseif ( count($individual_files) != count($individual_text)) {
echo "<li><img src='Blog-Albums/" . $row["sno"] ."/". $individual_files[$file_number] . "' alt='gallery image'/><div class='slider-caption'><p></p></div></li>";
}

PHP loop outputting duplicates

public function select(){
$rows = [];
$connection = $this->connect();
$result = $connection->query("SELECT username FROM users");
while ($row = $result->fetch_assoc()){
$rows[] = $row;
}
$userlist = 0;
foreach($rows as $username){
$userlist .= $username['username'];
}
$get_rankings = [1,2,3,4];
$get_image_path = "images/";
$total = 0;
for ($x = 0; $x < count($get_rankings); $x++){
$total = $get_rankings[$x];
$path .= "<img src = '" . $get_image_path . $total . ".png'>\n" . $userlist . "<br/>";
// echo "<span class = 'align-down'>{$path}";
// echo "<p class = 'user-name'> {$rows['0']}</p>";
// echo "</span>";
}
echo $path;
}
I'm trying to output a simple ranking but using the number index as images to display them.
In the past i've tried to do something similar but couldn't figure out how to match player it with images on the side.
The output im getting is this:
It's outputting each entry 4 times(I get why, its in a loop) but I can't figure out the correct solution to write it outside of a loop or properly
The desired output is:
My DataBase reads as:
[id][username][password]
If there is an easier solution, i'm all ears. I don't know how to approach this.
There's no need for $userlist. Output the username from $rows[$x].
$path = "";
$max = min(count($rows), count($get_rankings));
for ($x = 0; $x < $max; $x++){
$total = $get_rankings[$x];
$path .= "<img src = '" . $get_image_path . $total . ".png'>\n" . $rows[$x]['username'] . "<br/>";
// echo "<span class = 'align-down'>{$path}";
// echo "<p class = 'user-name'> {$rows['0']}</p>";
// echo "</span>";
}

How to get a html-table from an sql-query with various numbers of columns?

I have a html-form to read out data from an SQL-database. The number of selections is completely free, which means that there are no obligatory fields.
I would like to show the results that meet all selected criteria in a html-table. Here is my code:
<?php
include("../files/zugriff.inc.php");
if (isset($_POST["submit"])) {
$sent = $_POST['sent'];
$datenWerte = array();
$fruitname = $_POST["fruitname"];
$fruitgroup = $_POST["fruitgroup"];
$vegetablegroup = $_POST["vegetablegroup"];
$country = $_POST["country"];
$season = $_POST["season"];
$diameter = $_POST["diameter"];
$color = $_POST["color"];
if(!empty($fruitgroup)) {
$datenWerte['fruitgroup'] = $fruitgroup;
}
if(!empty($vegetablegroup)) {
$datenWerte['vegetablegroup'] = $vegetablegroup;
}
if(!empty($country)) {
$datenWerte['country'] = $country;
}
if(!empty($season)) {
$datenWerte['season'] = $season;
}
if(!empty($diameter)) {
$datenWerte['diameter'] = $diameter;
}
if(!empty($color)) {
$datenWerte['color '] = $color;
}
foreach ($datenWerte as $key => $value) {
$spalten[] = $key;
$werte[] = "'$value'";
}
echo "<b>Results:</b><br><br>";
$sql = "SELECT * FROM fruitdatabase WHERE (" . implode(", ",
$spalten) . ") = (" . implode(", ", $werte) . ")";
$result = mysqli_query($db, $sql);
$data = array();
while($row = $result->fetch_object()){
$data[] = $row;
}
// Numeric array with data that will be displayed in HTML table
$aray = $data;
$nr_elm = count($aray); // gets number of elements in $aray
// Create the beginning of HTML table, and of the first row
$html_table = '<table border="1 cellspacing="0" cellpadding="2""><tr>';
$nr_col = count($spalten); // Sets the number of columns
// If the array has elements
if ($nr_elm > 0) {
// Traverse the array with FOR
for($i=0; $i<$nr_elm; $i++) {
$html_table .= '<td>' .$aray[$i]. '</td>'; // adds the value in
column in table
// If the number of columns is completed for a row (rest of
division of ($i + 1) to $nr_col is 0)
// Closes the current row, and begins another row
$col_to_add = ($i+1) % $nr_col;
if($col_to_add == 0) { $html_table .= '</tr><tr>'; }
}
// Adds empty column if the current row is not completed
if($col_to_add != 0) $html_table .= '<td colspan="'. ($nr_col -
$col_to_add). '"> </td>';
}
$html_table .= '</tr></table>'; // ends the last row, and the table
// Delete posible empty row (<tr></tr>) which cand be created after last
column
$html_table = str_replace('<tr></tr>', '', $html_table);
echo $html_table; // display the HTML table
}
mysqli_close($db);
?>
Unfortunately, it´s not working. Could somebody please help me to find the error?
Than you very much in advance!

how to have two images in one row in php from array

Please help me I have just pulled images from gallery using PHP. But now I just want to display two images in one row. Return it in $content that I have specified.
Please help me.
function CreateGalleryImages($types) {
$galleryArray = array();
$galleryModel = new GalleryModel();
$galleryArray = ($galleryModel -> getGalleryByTypes($types));
$result = "";
foreach ($galleryArray as $gallery) {
for ($i = 0; $i < 2; $i++){
$result = "<td>"
."<img runat = 'server' src = 'http://localhost/schoolwb/event/$gallery' height=500 width=500 />"
."</td>";
}
$result = "<tr>.$result.</tr>";
}
return "<table class = 'GalleryTable'> . $result . </table>";
}
You have to concatenate the result and to store in $result.
Try This
<?php
function CreateGalleryImages($types){
$galleryArray = array();
$galleryModel = new GalleryModel();
$galleryArray = ($galleryModel->getGalleryByTypes($types));
$result = "";
foreach ($galleryArray as $gallery){
$cl = "";
for ($i = 0;$i<2;$i++){
$cl .= "<td>"
."<img runat = 'server' src = 'http://localhost/schoolwb/event/$gallery' height=500 width=500 />"
."</td>";
}
$result .= "<tr>.$cl.</tr>";
}
return "<table class = 'GalleryTable'>.$result.</table>";
}
?>

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";

Categories