Pagination in PHP with N number of elements per page - php

I need a little bit of help.
I have an XML file as a database. From it, I need to create a pagination with 25 elements per page with Next and Previous buttons, but with my skills I'm stuck at it.
At the moment, I've written this code, but every page it reset the ID from the database to 0, so it doesn't work.
<?php
$xml = simplexml_load_file("SITE_URL/database_gamecard.xml");
$ids = array();
$count = 0;
foreach($xml->gamecard as $id) {
$ids[] = $id;
}
//Order IDs by url names
//usort ($ids, function($a, $b) {
//$url = $id->url;
//return strcmp($a[$url], $b[$url]);
//});
function PopulatePage($id) {
$url = $id->url;
$img = $id->img;
echo '<a class="darken" href="' . $url . '"><img width="320" height="240" src="' . $img . '"></a>';
}
function StopCount() {
$page = intval($_GET['page']);
$pageurl = "SITE_URL/list.php?page=";
$count = 0;
$page = $page + 1;
$newurl = $pageurl . $page;
echo "<a href='" . $newurl . "'>Next</a>";
}
//Test generating pages
foreach ($ids as $id) {
$count++;
if($page == 1) {
PopulatePage($id);
if($count == 25) {
StopCount();
break;
}
}
if($page == 2) {
PopulatePage($id);
if($count == 25) {
StopCount();
break;
}
}
}
?>

Related

PHP - Search with Pagination

So I have these two PHP files products.php and receive.php .
What my problem is I want to use Ajax on displaying the products with search and paginates also. The code below works though but only if I use a GET. Is it possible to submit only the page number and refreshes only the div (where products loop) and not the whole page so that my POST requests (from search values - title, keywords) will still hold? coz if I use GET on pagination, the POST requests are getting empty after clicking the second page.
receive.php
$pdo_sql = 'SELECT * FROM items WHERE item_title LIKE %$keyword% OR keywords LIKE %$keyword% ORDER BY id DESC ';
/*** Pagination Code starts ***/
$per_page_html = '';
$page = 1;
$start=0;
// Get Page Number
if(!empty($_GET["page"])) {
$page = $_GET["page"];
$start=($page-1) * ROW_PER_PAGE;
}
// Adds Limit to Query then Execute
$limit=" LIMIT " . $start . "," . ROW_PER_PAGE;
$pagination_statement = $pdo_conn->prepare($pdo_sql);
$pagination_statement->bindValue(':keyword', '%' . $keyword . '%', PDO::PARAM_STR);
$pagination_statement->execute();
// Count the total number of rows
$row_count = $pagination_statement->rowCount();
if(!empty($row_count)){
$total_links=ceil($row_count/ROW_PER_PAGE);
$previous_link = $next_link = $page_link = '';
if($total_links > 4)
{
if($page < 5)
{
for($count = 1; $count <= 5; $count++)
{
$page_array[] = $count;
}
$page_array[] = '...';
$page_array[] = $total_links;
}
else
{
$end_limit = $total_links - 5;
if($page > $end_limit)
{
$page_array[] = 1;
$page_array[] = '...';
for($count = $end_limit; $count <= $total_links; $count++)
{
$page_array[] = $count;
}
}
else
{
$page_array[] = 1;
$page_array[] = '...';
for($count = $page - 1; $count <= $page + 1; $count++)
{
$page_array[] = $count;
}
$page_array[] = '...';
$page_array[] = $total_links;
}
}
}
else
{
for($count = 1; $count <= $total_links; $count++)
{
$page_array[] = $count;
}
}
for($count = 0; $count < count($page_array); $count++)
{
if($page == $page_array[$count])
{
// Current Page = Selected Page
$page_link .= '<a class="paginate_current" href="javascript:void(0)">'.$page_array[$count].'</a>';
$previous_id = $page_array[$count] - 1;
if($previous_id > 0)
{
// Previous Button Enable
$previous_link = '<a class="paginate_prev" href="products.php?page='.$previous_id.'">Previous</a>';
}
else
{
// Previous Button Disabled
$previous_link = '<a class="paginate_prev-disabled" href="javascript:void(0)">Previous</a>';
}
$next_id = $page_array[$count] + 1;
if($next_id > $total_links)
{
// Next Button Disabled
$next_link = '<a class="paginate_next-disabled" href="javascript:void(0)">Next</a>';
}
else
{
// Next Button Enabled
$next_link = '<a class="paginate_next" href="products.php?page='.$next_id.'">Next</a>';
}
}
else
{
if($page_array[$count] == '...')
{
// Ellipsis
$page_link .= '<a class="paginate_ellipsis" href="javascript:void(0)">...</a>';
}
else
{
// Pages
$page_link .= '<a class="paginate_pages" href="products.php?page='.$page_array[$count].'">'.$page_array[$count].'</a>';
}
}
}
$per_page_html .= '<div class="text-center paginate">';
$per_page_html .= $previous_link . $page_link . $next_link;
$per_page_html .= '</div>';
}
$query = $pdo_sql.$limit;
$pdo_statement = $pdo_conn->prepare($query);
$pdo_statement->bindValue(':keyword', '%' . $keyword . '%', PDO::PARAM_STR);
$pdo_statement->execute();
$pdo_result = $pdo_statement->fetchAll();
products.php
<div class="row">
<div class="col">
<div class="products_container grid" id="refresh">
<?php
if(!empty($pdo_result)) {
foreach($pdo_result as $pdo_row) {
$id = $pdo_row['id'];
$name = $pdo_row['item_title'];
$img = $pdo_row['item_img'];
$price = $pdo_row['item_price'];
$sold = $pdo_row['item_sold'];
$stocks = $pdo_row['stocks'];
$date = $pdo_row['date'];
if ($sold >= $max && $date != date("Y-m-d") ) {
$sort = 'hot';
}else if($date == date("Y-m-d") && $sold <= $max){
$sort = 'new';
}else{
$sort = '';
}
echo '
<div class="product grid-item '.$sort.'">
<div class="product_inner">
<div class="product_image">
<img src="'.$img.'" alt="">
<div class="product_tag">'.$sort.'</div>
</div>
<div class="product_content text-center">
<div class="product_title text-long">'.$name.'</div>
<div class="product_price">₱'.number_format($price).'</div>
<div class="product_button ml-auto mr-auto trans_200">
<button class="product_button ml-auto mr-auto trans_200" id="add2c" data-prod=" '.$id.' " type="button" >add to cart</button>
</div>
</div>
</div>
</div>
';
} //End Foreach Loop
}
else{
echo "no products found";
}
?>
</div>
</div>
</div>
<!-- PAGINATION HERE -->
<?php echo $per_page_html; ?>
Method 1 => Without ajax
You can use the GET method for search value also. and in every pagination link
append the search value too.
for example.
$next_link = '<a class="paginate_next" href="products.php?page='.$next_id.'">Next</a>';
instead of above line use below one.
$next_link = '<a class="paginate_next" href="products.php?page='.$next_id.'&search='.$keyword.'">Next</a>';
Method 2 => using ajax
instead of href use a javascript function like below
$next_link = '<a class="paginate_next" href="#" onclick="paginate_fn(\''.$next_id.'\', \''.$keyword.'\'">Next</a>'
<script>
function paginate_fn(pageID, keyword){
$.ajax({
async: true,
type: 'get', // you can use post also
dataType:'json',
data: {'pageID':pageID, 'keyword': keyword},
url: "paget_name.php", // your page name
success: function (data) {
$('#search-content').html( data['content'] );
},
error: function () {
alert('An Error Occurred!.');
}
});
}
</script>

Custom table sorting not working correct

I am creating a data table that has sortable links but when I click on the link say "username" if i click on that multiple times it makes the url have lots of asc example: http://localhost/riwakawebsitedesigns-website/admin/users/status/ascascascascascascasc it should just be
Sorting Asc http://localhost/riwakawebsitedesigns-website/admin/users/status/asc
And then if click again and so on.
Sorting Desc http://localhost/riwakawebsitedesigns-website/admin/users/status/desc
This here is how pagination looks in url http://localhost/riwakawebsitedesigns-website/admin/users/1
I cannot figure out why each time i click on table head link that it creates so many asc etc. How can I fix it.
What's wrong with sort code. The pagination works fine. Please note I have use codeigniter pagination but not to my liking.
<?php
class Users extends MX_Controller {
public function index() {
$this->getList();
}
public function getList() {
$this->load->library('paginations');
$sort_segment = $this->uri->segment(3);
if (isset($sort_segment)) {
$sort = $sort_segment;
} else {
$sort = 'username';
}
$order_segment = $this->uri->segment(3);
if (isset($order_segment)) {
$order = $order_segment;
} else {
$order = 'asc';
}
$page_segment = $this->uri->segment(4);
if (isset($page_segment)) {
$page = $page_segment;
} else {
$page = 1;
}
$url = '';
if (isset($sort_segment)) {
$url .= $sort_segment;
}
if (isset($order_segment)) {
$url .= $order_segment;
}
if (isset($page_segment)) {
$url .= $page_segment;
}
$data['title'] = "Users";
$this->load->model('admin/user/model_user');
$admin_limit = "1";
$filter_data = array(
'sort' => $sort,
'order' => $order,
'start' => ($page - 1) * $admin_limit,
'limit' => $admin_limit
);
$user_total = $this->model_user->getTotalUsers();
$results = $this->model_user->getUsers($filter_data);
foreach ($results as $result) {
$data['users'][] = array(
'user_id' => $result['user_id'],
'username' => $result['username'],
'date_added' => $result['date_added'],
'edit' => site_url('admin/users/edit' .'/'. $result['user_id'])
);
}
$url = '';
if ($order == 'asc') {
$url .= 'desc';
} else {
$url .= 'asc';
}
if (isset($page_segment)) {
$url .= $page_segment;
}
$data['sort_username'] = site_url('admin/users' .'/'. 'username' .'/'. $url);
$data['sort_status'] = site_url('admin/users' .'/'. 'status' .'/'. $url);
$data['sort_date_added'] = site_url('admin/users' .'/'. 'date_added' .'/'. $url);
$url = '';
if (isset($sort_segment)) {
$url .= $sort_segment;
}
if (isset($order_segment)) {
$url .= $order_segment;
}
$paginations = new Paginations();
$paginations->total = $user_total;
$paginations->page = $page;
$paginations->limit = "1";
$paginations->url = site_url('admin/users' .'/'. $url .'/'. '{page}');
$data['pagination'] = $paginations->render();
$paginations_lang = "Showing %d to %d of %d (%d Pages)";
$data['results'] = sprintf($paginations_lang, ($user_total) ? (($page - 1) * $admin_limit) + 1 : 0, ((($page - 1) * $admin_limit) > ($user_total - $admin_limit)) ? $user_total : ((($page - 1) * $admin_limit) + $admin_limit), $user_total, ceil($user_total / $admin_limit));
$data['sort'] = $sort;
$data['order'] = $order;
$this->load->view('template/user/users_list.tpl', $data);
}
}
My Library
<?php
class Paginations {
public $total = 0;
public $page = 1;
public $limit = 20;
public $num_links = 8;
public $url = '';
public $text_first = '|<';
public $text_last = '>|';
public $text_next = '>';
public $text_prev = '<';
public function render() {
$total = $this->total;
if ($this->page < 1) {
$page = 1;
} else {
$page = $this->page;
}
if (!(int)$this->limit) {
$limit = 10;
} else {
$limit = $this->limit;
}
$num_links = $this->num_links;
$num_pages = ceil($total / $limit);
$this->url = str_replace('%7Bpage%7D', '{page}', $this->url);
$output = '<ul class="pagination">';
if ($page > 1) {
$output .= '<li>' . $this->text_first . '</li>';
$output .= '<li>' . $this->text_prev . '</li>';
}
if ($num_pages > 1) {
if ($num_pages <= $num_links) {
$start = 1;
$end = $num_pages;
} else {
$start = $page - floor($num_links / 2);
$end = $page + floor($num_links / 2);
if ($start < 1) {
$end += abs($start) + 1;
$start = 1;
}
if ($end > $num_pages) {
$start -= ($end - $num_pages);
$end = $num_pages;
}
}
for ($i = $start; $i <= $end; $i++) {
if ($page == $i) {
$output .= '<li class="active"><span>' . $i . '</span></li>';
} else {
$output .= '<li>' . $i . '</li>';
}
}
}
if ($page < $num_pages) {
$output .= '<li>' . $this->text_next . '</li>';
$output .= '<li>' . $this->text_last . '</li>';
}
$output .= '</ul>';
if ($num_pages > 1) {
return $output;
} else {
return '';
}
}
}
Thanks so much to #AdrienXL which gave me the idea what problem was.
I now have fixed it. I had doubled up on my page and sort and orders $_GET. So there for i have now just used uri segments and removed the doubled up code and change a couple of things in model
For people who do not want to use codeigniter pagination class.
You can use my example:
My Users:
<?php
class Users extends MX_Controller {
public function index() {
$this->load->library('paginations');
$this->load->model('admin/user/model_user');
// Sort
if (null !==($this->uri->segment(3))) {
$sort = $this->uri->segment(3);
} else {
$sort = 'username';
}
// Order
if (null !==($this->uri->segment(4))) {
$order = $this->uri->segment(4);
} else {
$order = 'asc';
}
// Page
if (null !==($this->uri->segment(3))) {
$page = $this->uri->segment(3);
} else {
$page = 1;
}
$url = '';
// Sort
if (null !==($this->uri->segment(3))) {
$url .= $this->uri->segment(3);
}
// Order
if (null !==($this->uri->segment(4))) {
$url .= $this->uri->segment(4);
}
// Page Number
if (null !==($this->uri->segment(3))) {
$url .= $this->uri->segment(3);
}
$admin_limit = "1";
$filter_data = array(
'sort' => $sort,
'order' => $order,
'start' => ($page - 1) * $admin_limit,
'limit' => $admin_limit
);
$user_total = $this->model_user->getTotalUsers();
$results = $this->model_user->getUsers($filter_data);
foreach ($results as $result) {
$data['users'][] = array(
'user_id' => $result['user_id'],
'username' => $result['username'],
'status' => ($result['status'] ? "Enabled" : "Disabled"),
'date_added' => date(strtotime($result['date_added'])),
'edit' => site_url('admin/users/edit' .'/'. $result['user_id'] . $url)
);
}
$url = '';
if ($order == 'asc') {
$url .= 'desc';
} else {
$url .= 'asc';
}
$data['sort_username'] = site_url('admin/users' .'/'. 'username' .'/'. $url);
$data['sort_status'] = site_url('admin/users' .'/'. 'status' .'/'. $url);
$data['sort_date_added'] = site_url('admin/users' .'/'. 'date_added' .'/'. $url);
$url = '';
$paginations = new Paginations();
$paginations->total = $user_total;
$paginations->page = $page;
$paginations->limit = $admin_limit;
$paginations->url = site_url('admin/users' .'/'. $url . '{page}');
$data['pagination'] = $paginations->render();
$paginations_lang = "Showing %d to %d of %d (%d Pages)";
$data['results'] = sprintf($paginations_lang, ($user_total) ? (($page - 1) * $admin_limit) + 1 : 0, ((($page - 1) * $admin_limit) > ($user_total - $admin_limit)) ? $user_total : ((($page - 1) * $admin_limit) + $admin_limit), $user_total, ceil($user_total / $admin_limit));
$data['sort'] = $sort;
$data['order'] = $order;
$this->load->view('template/user/users_list.tpl', $data);
}
}
My View
<div class="table-responsive">
<table class="table table-striped table-bordered table-hover">
<thead>
<tr>
<td class="text-left"><?php if ($sort == 'username') { ?>
Username
<?php } else { ?>
Username
<?php } ?></td>
<td class="text-left"><?php if ($sort == 'status') { ?>
Status
<?php } else { ?>
Status
<?php } ?></td>
<td class="text-left"><?php if ($sort == 'date_added') { ?>
Date Added
<?php } else { ?>
Date Added
<?php } ?></td>
<td class="text-right">Action</td>
</tr>
</thead>
<tbody>
<?php foreach ($users as $user) { ?>
<tr>
<td><?php echo $user['username'];?></td>
<td><?php echo $user['status'];?></td>
<td><?php echo $user['date_added'];?></td>
<td><a href="<?php echo $user['edit'];?>">Edit</td>
</tr>
<?php } ?>
</tbody>
</table>
<div class="row">
<div class="col-sm-6 text-left"><?php echo $pagination; ?></div>
<div class="col-sm-6 text-right"><?php echo $results; ?></div>
</div>
</div>
Model Function
public function getUsers($data = array()) {
$sql = "SELECT * FROM `" . $this->db->dbprefix . "user`";
$sort_data = array(
'username',
'status',
'date_added'
);
if (isset($data['sort']) && in_array($data['sort'], $sort_data)) {
$sql .= " ORDER BY " . $data['sort'];
} else {
$sql .= " ORDER BY username";
}
if (isset($data['order']) && ($data['order'] == 'desc')) {
$sql .= " desc";
} else {
$sql .= " asc";
}
if (isset($data['start']) || isset($data['limit'])) {
if ($data['start'] < 0) {
$data['start'] = 0;
}
if ($data['limit'] < 1) {
$data['limit'] = 20;
}
$sql .= " LIMIT " . (int)$data['start'] . "," . (int)$data['limit'];
}
$query = $this->db->query($sql);
return $query->result_array();
}
Routes:
$route['admin/users'] = "admin/user/users/index";
$route['admin/users/edit/(:any)'] = "admin/user/users/edit/$1";
$route['admin/users/(:any)'] = "admin/user/users/index/$1";
$route['admin/users/(:any)/(:any)/(:any)'] = "admin/user/users/index/$1/$2/$3";
Custom Library
<?php
class Paginations {
public $total = 0;
public $page = 1;
public $limit = 20;
public $num_links = 8;
public $url = '';
public $text_first = '|<';
public $text_last = '>|';
public $text_next = '>';
public $text_prev = '<';
public function render() {
$total = $this->total;
if ($this->page < 1) {
$page = 1;
} else {
$page = $this->page;
}
if (!(int)$this->limit) {
$limit = 10;
} else {
$limit = $this->limit;
}
$num_links = $this->num_links;
$num_pages = ceil($total / $limit);
$this->url = str_replace('%7Bpage%7D', '{page}', $this->url);
$output = '<ul class="pagination">';
if ($page > 1) {
$output .= '<li>' . $this->text_first . '</li>';
$output .= '<li>' . $this->text_prev . '</li>';
}
if ($num_pages > 1) {
if ($num_pages <= $num_links) {
$start = 1;
$end = $num_pages;
} else {
$start = $page - floor($num_links / 2);
$end = $page + floor($num_links / 2);
if ($start < 1) {
$end += abs($start) + 1;
$start = 1;
}
if ($end > $num_pages) {
$start -= ($end - $num_pages);
$end = $num_pages;
}
}
for ($i = $start; $i <= $end; $i++) {
if ($page == $i) {
$output .= '<li class="active"><span>' . $i . '</span></li>';
} else {
$output .= '<li>' . $i . '</li>';
}
}
}
if ($page < $num_pages) {
$output .= '<li>' . $this->text_next . '</li>';
$output .= '<li>' . $this->text_last . '</li>';
}
$output .= '</ul>';
if ($num_pages > 1) {
return $output;
} else {
return '';
}
}
}

Php Pagination class and display issue

I have a php pagination class with code as follows:
<?php
class Pagination {
private $num_pages = 1;
private $start = 0;
private $display;
private $start_display;
function __construct ($query, $display=10) {
if (!empty($query)) {
$this->display = $display;
if (isset($_GET['display']) && is_numeric($_GET['display'])) $this->display = (int) $_GET['display'];
if (isset($_GET['np']) && is_numeric($_GET['np']) && $_GET['np'] > 0) {
$this->num_pages = (int) $_GET['np'];
} else {
if (is_numeric($query)) {
$num_records = $query;
} else {
$result = db_query ($query);
if ($result->num_rows > 1 || strstr($query, 'COUNT') === false) {
$num_records = $result->num_rows;
} else {
$row = $result->fetch_row();
$num_records = $row[0];
}
}
if ($num_records > $this->display) $this->num_pages = ceil ($num_records/$this->display);
}
if (isset($_GET['s']) && is_numeric($_GET['s']) && $_GET['s'] > 0) $this->start = (int) $_GET['s'];
$this->start_display = " LIMIT {$this->start}, {$this->display}";
}
}
public function display ($split=5) {
global $page;
$html = '';
if ($this->num_pages <= 1) return $html;
//$page->link('pagination.css');
$url = $page->url ('add', '', 'np', $this->num_pages);
$current_page = ($this->start/$this->display) + 1;
$begin = $current_page - $split;
$end = $current_page + $split;
if ($begin < 1) {
$begin = 1;
$end = $split * 2;
}
if ($end > $this->num_pages) {
$end = $this->num_pages;
$begin = $end - ($split * 2);
$begin++; // add one so that we get double the split at the end
if ($begin < 1) $begin = 1;
}
if ($current_page != 1) {
$html .= '<a class="first" title="First" href="' . $page->url('add', $url, 's', 0) . '">«</a>';
$html .= '<a class="prev" title="Previous" href="' . $page->url('add', $url, 's', $this->start - $this->display) . '">Previous</a>';
} else {
$html .= '<span class="disabled first" title="First">«</span>';
$html .= '<span class="disabled prev" title="Previous">Previous</span>';
}
for ($i=$begin; $i<=$end; $i++) {
if ($i != $current_page) {
$html .= '<a title="' . $i . '" href="' . $page->url('add', $url, 's', ($this->display * ($i - 1))) . '">' . $i . '</a>';
} else {
$html .= '<span class="current">' . $i . '</span>';
}
}
if ($current_page != $this->num_pages) {
$html .= '<a class="next" title="Next" href="' . $page->url('add', $url, 's', $this->start + $this->display) . '">Next</a>';
$last = ($this->num_pages * $this->display) - $this->display;
$html .= '<a class="last" title="Last" href="' . $page->url('add', $url, 's', $last) . '">»</a>';
} else {
$html .= '<span class="disabled next" title="Next">Next</span>';
$html .= '<span class="disabled last" title="Last">»</span>';
}
return '<div class="pagination">' . $html . '</div>';
}
public function limit () {
return $this->start_display;
}
}
?>
I am calling the class as follows:
$page->link('pagination.css');
$links = new Pagination ($numrows);
I have a mysql query with LIMIT as $links->limit() and it is displaying 10 records correctly.
I am calling pagination display as:
$html .= $links->display();
But no pagination is displayed and I am getting the following error:
PHP Notice: Undefined variable: page in ......
and
Call to a member function link() on a non-object on line
$page->link('pagination.css');
I have the pagination.css file uploaded in the same folder too....
What is wrong with my code ?? Why am i getting the Notice that php is undefined variable though having a global scope in the class method? And Call to a member function link() on a non-object ??
Thanks in advance.
Note: Got the pagination Class from the following link:
Pagination Class Source
You have created an Class Definition, but never created an Instance of this Class Definition.
you have to instantiate class ?$page? in PHP to get an Instance in form of an object of it. For your example code you have to hold (save) this object instance in an variable with name "page" which was previously defined with global keyword.
$html = "";
global $page;
$page->link('pagination.css');
$links = new Pagination ($numrows);
$html .= $page->display();
var_dump($html);
HTH
Tobias

Build one object from foreach loop

I want to take an array I build from a result set, encode it and then put it into a single object. My problem is I am making a lot of objects, but I want all my data to be in one object. The problem is that I echo out multiple objects from my json encode on my foreach loop. How would I take all that data I get out of that foreach loop and put it into one object? Any help is appreciated. Below is my code. Basically, what I need is this.
{"item1":"itemdata","category":"mycategory"}
but all in one object. I don't want multiple {} {} {}
$counter = 0;
$itemID = '';
foreach ($resultsTwo as $result) {
if ($counter >= 0 && $itemID != $result['item_id']) {
$description = $result['item_desc'];
$ID = substr($result['item_id'], 3, 6);
if ($result['bidder'] == 9999999999) {
$bid = $result['amount_bid'] + $result['min_bid_increment'];
} else {
$bid = preg_replace('~\.0+$~','',$result['amount_bid']);
}
//echo $ID . ' ' . $bid . '<br />';
$build['bid'] = $bid;
$build['id'] = $ID;
$build['item_desc'] = $description;
}
$itemID = $result['item_id'];
$counter++;
echo json_encode($build);
}
Create an array to hold the smaller arrays before your loop.
$fullData = array();
Then, inside your loop after you finish your build array add the build array to the fullData array.
$fullData[] = $build;
remove your current json_encode() and then, outside the loop.
echo json_encode($fullData);
This is what it would be changed to:
<?php
$counter = 0;
$itemID = '';
$fullData = array();
foreach ($resultsTwo as $result) {
if ($counter >= 0 && $itemID != $result['item_id']) {
$description = $result['item_desc'];
$ID = substr($result['item_id'], 3, 6);
if ($result['bidder'] == 9999999999) {
$bid = $result['amount_bid'] + $result['min_bid_increment'];
} else {
$bid = preg_replace('~\.0+$~','',$result['amount_bid']);
}
//echo $ID . ' ' . $bid . '<br />';
$build['bid'] = $bid;
$build['id'] = $ID;
$build['item_desc'] = $description;
}
$itemID = $result['item_id'];
$counter++;
$fullData[] = $build;
}
echo json_encode($fullData);
?>
Change this
$counter = 0;
$itemID = '';
foreach ($resultsTwo as $result) {
if ($counter >= 0 && $itemID != $result['item_id']) {
$description = $result['item_desc'];
$ID = substr($result['item_id'], 3, 6);
if ($result['bidder'] == 9999999999) {
$bid = $result['amount_bid'] + $result['min_bid_increment'];
} else {
$bid = preg_replace('~\.0+$~','',$result['amount_bid']);
}
//echo $ID . ' ' . $bid . '<br />';
$build['bid'] = $bid;
$build['id'] = $ID;
$build['item_desc'] = $description;
}
$itemID = $result['item_id'];
$counter++;
echo json_encode($build);
}
To
$counter = 0;
$itemID = '';
foreach ($resultsTwo as $result) {
if ($counter >= 0 && $itemID != $result['item_id']) {
$description = $result['item_desc'];
$ID = substr($result['item_id'], 3, 6);
if ($result['bidder'] == 9999999999) {
$bid = $result['amount_bid'] + $result['min_bid_increment'];
} else {
$bid = preg_replace('~\.0+$~','',$result['amount_bid']);
}
//echo $ID . ' ' . $bid . '<br />';
$build[] = array('bid'=>$bid,'id'=>$ID,'item_desc'=>$description);
}
$itemID = $result['item_id'];
$counter++;
}
echo json_encode($build);

php report is very slow and crashes in firefox

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)

Categories