How do I pass additional parameter in the url for pagination to work
my existing page link is http://localhost/site/wp-admin/admin.php?page=myPage
how do i create the syntax / logic in PHP to add &pagenum=1 in the url?
currently i have this code
global $wpdb;
$per_page = 6;
$page_query = $wpdb->get_var("SELECT COUNT('id') FROM form");
$pages = ceil($page_query / $per_page);
$currentPage = (isset ($_GET['pagenum'])) ? (int)$_GET['pagenum'] : 1;
$start = ($currentPage -1 ) * $per_page;
$row = $wpdb->get_results("SELECT * FROM form LIMIT $start , $per_page");
//foreach loop here
$pagenum = 1;
$url = "http://localhost/site/wp-admin/admin.php?page=myPage" . "&pagenum=".$pagenum;
Try this::
First build an array of data you want to transfer like--
$data=array(
"param1"=>"value1",
"param2"=>"value2"
);
Then use http_build_queryto convert data to url format!!
$url_data=http_build_query($data);
$target_url="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; // your url here
if(strpos($target_url,"?")==false){
$target_url.="?";
}else{
$target_url.="&";
}
$target_url.=$url_data;
$page='MyPage';
$pagenum = 1;
$url = "http://localhost/site/wp-admin/admin.php?page=".$page."&pagenum=".$pagenum;
Related
I'm working on a simple vlog site project and I'm trying to show only 20 video thumbnail per page and I've wrote this code in the index to divide the videos to multiple pages and then pagination them ... the problem is that it shows the same first video's thumbnail 20 times per page for infinity pages.
I really need help with this code
<?php
require_once ('db.php') ;
require_once ('VideosApi.php') ;
$count = mysql_query('SELECT COUNT(id) AS numb FROM videos ORDER BY id');
$array = mysql_fetch_assoc($count);
$number = $array['numb'];
mysql_free_result($count);
$PerPage = 20;
$nbPage = ceil(abs($number/$PerPage));
if(isset($_GET['page']) && $_GET['page'] > 0 && $_GET['page'] <= $nbPage && preg_match('#^[0-9]+$#',$_GET['page'])){ $cPage = $_GET['page']; }
else{ $cPage = 1; }
$Query = mysql_query('SELECT * FROM Videos ORDER BY id LIMIT '.(($cPage-1) * $PerPage).','.$PerPage);
$videos = Videos_Get() ;
if ($videos == Null)
die ('problem');
$vcount = #count ($videos) ;
if ($vcount == 0)
die('no videos') ;
For ($i = 0; $i < $vcount; $i++)
{
$video = $videos [$i];
if ($video->time > 3600)
$duration = gmdate("H:i:s",$video->time);
else
$duration = gmdate("i:s",$video->time);
while($Rows = mysql_fetch_assoc($Query)){
echo ( "<div class=\"video\">
<img src=\"$video->img\"><span class=\"class-video-name\">$video->name</span>
<div class=\"class-video-footer\">
<span class=\"class-video-duration\">$duration</span>
</div>
</div>") ; }
} ?>
A few tips before we get to the answer proper:
Don't use mysql_*. That family of functions is now deprecated and support will be dropped in future versions of PHP. For code longevity, consider using MySQLi or PDO.
Use is_numeric() to check if a string has a numeric value. Using preg_match() is very load heavy for such a simple task.
Try to avoid using SELECT * inside of MySQL queries. Very rarely do you need everything from the table so fetching all fields for rows is very inefficient (especially if you're not using indexes optimally).
That having been said, I've taken some time to rewrite your code following the practices I've preached above. Below is the modified code, and underneath that an explanation of what was wrong:
Update db.php as follows:
<?php
$db = new PDO( 'mysql:dbname=DATABASE_NAME;host=127.0.0.1', 'DATABASE_USER', 'DATABASE_PASSWORD' );
?>
Now for your main file:
<?php
require_once 'db.php';
require_once 'VideosApi.php';
$count = $db->query( 'SELECT COUNT(id) AS total FROM videos' )->fetchObject();
$number = $count->total;
$perPage = 20;
$pages = ceil( $number / $perPage );
$page = ( isset($_GET['page']) ) ? $_GET['page'] : 1;
$page = ( $page < 1 || $page > $pages || !is_numeric($page) ) ? 1 : $page;
$offset = ($page - 1) * $perPage;
$query = $db->query( 'SELECT id, img, name, time FROM videos ORDER BY id LIMIT '.$offset.','.$perPage );
if( $query->rowCount() < 1 )
{
die( 'No videos' );
}
$html = '';
while( $video = $query->fetchObject() )
{
$duration = ($video->time > 3600) ? gmdate('H:i:s', $video->time) : gmdate('i:s', $video->time);
$html.= '<div class="video">';
$html.= "\n\t".'<a href=\"video.php?id='.$video->id.'">';
$html.= "\n\t\t".'<img src="'.$video->img.'" />';
$html.= "\n\t".'</a>';
$html.= "\n\t".'<span class="class-video-name">'.$video->name.'</span>';
$html.= "\n\t".'<div class="class-video-footer">';
$html.= "\n\t\t".'<span class="class-video-duration">'.$duration.'</span>';
$html.= "\n\t".'</div>';
$html.= "\n".'</div>';
}
echo $html;
?>
The problem with your original code is a little hard to determine since you do not provide the contents of VideosApi.php, which is where I assume you define Videos_Get(). Anyway, what I suspect is happening, is that Videos_Get() is actually ignoring all of your pagination, but as I say, it's difficult to diagnose because we can't see all of your code!
I'm making a Laravel Pagination based from my query result and be rendered in my view. I'm following this guide http://laravel.com/docs/5.1/pagination but I get an error:
Call to a member function paginate() on a non-object
I'm using query builder so I think that should be ok? Here's my code
public function getDeliveries($date_from, $date_to)
{
$query = "Select order_confirmation.oc_number as oc,
order_confirmation.count as cnt,
order_confirmation.status as stat,
order_confirmation.po_number as pon,
order_summary.date_delivered as dd,
order_summary.delivery_quantity as dq,
order_summary.is_invoiced as iin,
order_summary.filename as fn,
order_summary.invoice_number as inum,
order_summary.oc_idfk as ocidfk,
order_summary.date_invoiced as di
FROM
order_confirmation,order_summary
where order_confirmation.id = order_summary.oc_idfk";
if (isset($date_from)) {
if (!empty($date_from))
{
$query .= " and order_summary.date_delivered >= '".$date_from."'";
}
}
if (isset($date_to)) {
if (!empty($date_to))
{
$query .= " and order_summary.date_delivered <= '".$date_to."'";
}
}
$query.="order by order_confirmation.id ASC";
$data = DB::connection('qds106')->select($query)->paginate(15);
return $data;
}
However when I remove the paginate(15); it works fine.
Thanks
in the doc at this page: http://laravel.com/docs/5.1/pagination
we can see that we are not forced to use eloquent.
$users = DB::table('users')->paginate(15);
but, be sure you don't make a groupBy in your query because, the paginate method uses it.
after i'm no sure you can use paginate with query builder ( select($query) )
--- edit
You can create collection an use the paginator class :
$collection = new Collection($put_your_array_here);
// Paginate
$perPage = 10; // Item per page
$currentPage = Input::get('page') - 1; // url.com/test?page=2
$pagedData = $collection->slice($currentPage * $perPage, $perPage)->all();
$collection= Paginator::make($pagedData, count($collection), $perPage);
and in your view just use $collection->render();
public function getDeliveries($date_from, $date_to)
{
$query="your_query_here";
$deliveries = DB::select($query);
$deliveries = collect($deliveries);
$perPage = 10;
$currentPage = \Input::get('page') ?: 1;
$slice_init = ($currentPage == 1) ? 0 : (($currentPage*$perPage)-$perPage);
$pagedData = $users->slice($slice_init, $perPage)->all();
$deliveries = new LengthAwarePaginator($pagedData, count($deliveries), $perPage, $currentPage);
$deliveries ->setPath('set_your_link_page');
return $deliveries;
}
You set it by using the custom pagination..
$query = "Your Query here";
$page = 1;
$perPage = 5;
$query = DB::select($query);
$currentPage = Input::get('page', 1) - 1;
$pagedData = array_slice($query, $currentPage * $perPage, $perPage);
$query = new Paginator($pagedData, count($query), $perPage);
$query->setPath('Your Url');
$this->data['query'] = $query;
return view('Your_view_file', $this->data, compact('query'));
Here you can specify the path by using the setpath().
In your View
#foreach($query as $rev)
//Contents
#endforeach
<?php echo $Reviews->appends($_REQUEST)->render(); ?>
The appends will append the data.
Thank you.
this is the way i did, it use query builder and get the same result with pagination
$paginateNumber = 20;
$key = $this->removeAccents(strip_tags(trim($request->input('search_key', ''))));
$package_id = (int)$request->input('package_id', 0);
$movieHasTrailer = MovieTrailer::select('movie_id')->where('status','!=','-1')->distinct('movie_id')->get();
$movieIds = array();
foreach ($movieHasTrailer as $index => $value) {
$movieIds[] = $value->movie_id;
}
$keyparams = array();
$packages = Package::select('package_name','id')->get();
$whereClause = [
['movie.status', '!=', '-1'],
['movie_trailers.status', '!=', '-1']
];
if(!empty($key)){
$whereClause[] = ['movie.title', 'like', '%'.$key.'%'];
$keyparams['search_key'] = $key;
}
if($package_id !== 0){
$whereClause[] = ['movie.package_id', '=', $package_id];
$keyparams['package_id'] = $package_id;
}
$movies = DB::table('movie')
->leftJoin('movie_package','movie.package_id','=','movie_package.id')
->leftJoin('movie_trailers','movie.id','=','movie_trailers.movie_id')
->where($whereClause)
->whereIn('movie.id',$movieIds)
->select('movie.*','movie_package.package_name','movie_trailers.movie_id as movie_id',
DB::raw('count(*) as total_trailers, movie_id')
)
->groupBy('movie.id')
->paginate($paginateNumber);
If you need to hydrate, you can do this...
$pages = DB::table('stuff')
->distinct()
->paginate(24, ['stuff.id']);
$stuffs = Stuff::hydrate($pages->items());
return view('stuff.index')->with('stuffs', $stuffs)->with('pages', $pages)
$stuffs will contain your model object, $pages will contain your pagination, probably not the most efficient, but it works.
// import those Class into your Laravel Controller
use Illuminate\Pagination\Paginator;
use Illuminate\Support\Facades\Input;
use Illuminate\Database\Eloquent\Collection;
// In your public function
$query = DB::select(DB::raw("SELECT * FROM your_table"));
$collection = new Collection($query);
// Paginate
$perPage = 10; // Item per page
$currentPage = Input::get('page') - 1;
$pagedData = $collection->slice($currentPage * $perPage, $perPage)->all();
$pagination = new Paginator($pagedData, $perPage);
return response()->json([
$pagination
], 200);
I already using the pagination library in nearly ten modules, with no problems, but it fails in last one (and the most important).
My routing for this section is:
$route['candidate/sort/(:any)/(:any)/page/(:num)'] = 'candidate/sort/$1/$2/$3';
My Controller
public function sort($type, $id, $page = 1) {
/* Load Config */
$data = $this->data;
$data['sub_active'] = 'candidate';
$data['type'] = $type;
/* Get Candidates */
$total = $this->candidates->getTotal($type, $id);
if(($this->limit >= $total) && ($page > 1)) {
$data['candidates'] = $this->candidates->getCandidates(1, $this->limit, $type, $id);
}elseif(((($this->limit * $page) - $this->limit) >= $total) && ($page > 1)) {
$data['candidates'] = $this->candidates->getCandidates(ceil($total / $this->limit), $this->limit, $type, $id);
}else{
$data['candidates'] = $this->candidates->getCandidates($page, $this->limit, $type, $id);
}
/* Pagination */
$this->load->library('pagination');
# Config Pagination
$data['cms']['tables']['total_rows'] = $total;
$data['cms']['tables']['per_page'] = $this->limit;
$data['cms']['tables']['first_url'] = base_url($data['sub_active'].'/sort'.'/'.$type.'/'.$id);
$data['cms']['tables']['base_url'] = base_url($data['sub_active'].'/sort'.'/'.$type.'/'.$id.'/page');
$data['page'] = $page;
$data['total_pages'] = ceil($total / $this->limit);
$data['total'] = $total;
# Initialize Pagination
$this->pagination->initialize($data['cms']['tables']);
$data['pagination'] = $this->pagination->create_links();
/* Display Template */
$this->twig->display('pages/list_candidate.htm', $data);
}
Base first url = myweb.com/candidate/sort/$type/$id and base url = myweb.com/candidate/sort/$type/$id/page
But the pagination doesn’t work, it always the same page (page 1 on this case). I'm using this same schema in other controllers and it works fine, only fails with this.
Thanks in advance.
I finally found the answer:
$config['uri_segment'] = 6;
That's because codeigniter does not detect well the URL.
Nice, I am glad you found the answer Tunnecino!
But I think its need to be further explained , why
According to our wonderful CI user guide, here is how we determine the uri_segment so not to make the same mistake again :)
$this->uri->segment(n)
Permits you to retrieve a specific segment. Where n is the segment number you wish to retrieve. Segments are numbered from left to right. For example, if your full URL is this:
http://example.com/index.php/news/local/metro/crime_is_up
The segment numbers would be this:
1.news
2.local
3.metro
4.crime_is_up
By default the function returns FALSE (boolean) if the segment does not exist. There is an optional second parameter that permits you to set your own default value if the segment is missing. For example, this would tell the function to return the number zero in the event of failure:
$product_id = $this->uri->segment(3, 0);
I am trying to implement a load more feature in a web app I am building.
When the app loads, it makes an ajax call to controller which retrieves the data from the database and then encodes them in JSON.
I am making use of limits and offsets in mysql query and I more data to be loaded as the user scrolls down.
This is the method in the controller which the ajax call is made to
function latest_pheeds($offset = 0) {
//Confirm if a user is logged before allowing access
if($this->isLogged())
{
//Limit
$limit = 20;
//user id
$user_id = $this->session->userdata('user_id');
//load pheeds
$dt = $this->pheed_model->get_latest_pheeds($limit,$offset);
$data = $dt['pheeds']; //data
$total = $dt['total']; //Total no of rows of data
$return['pheeds'] = $data;
echo json_encode($return); //encode in json
} else {
$this->output->set_status_header('401',"Attempting Unauthorized Access");
}
}
How do I break this data into pages, so I can simply pass the page no as argument to method via the ajax call to implement the load more with jQuery?
Calculate $offset by multiplying (page number - 1) with $limit:
$offset = ($page - 1) * $limit;
So if $page is 1, then it will be (1 - 1) * 20 = 0 * 20 = 0,
if $page is 2, then it will be (2 - 1) * 20 = 1 * 20 = 20
Also rename function parameter $offset to $page
[EDIT]
Also what i would do is to query one row more, than needed, so i can detect if there is next page, eg:
$dt = $this->pheed_model->get_latest_pheeds($limit + 1,$offset);
$next_page = false;
if (count($dt) > $limit) {
$next_page = true;
$dt = array_pop($dt); // Excluding the last row so it is same size as $limit
}
// More code....
$return['next_page_exists'] = $next_page;
I am looking for a php pagination class, I have used a rather simple one in the past and it is no longer supported.
I was wondering if anyone had any recommendations ?
It seems pointless to build my own when there are probably so many good ones out there.
After more searching I decided that before I use a frameworked version I should fully understand what is involved in a paginator. So I built one myself. Thanks for the suggestions though!
I would suggest Zend_Paginator for the following reasons
It's loosely coupled and doesn't require the entire library.
The ZF community is larger than the PEAR community and is actively running security audits on code, and releasing maintenance versions.
It separates data sources by using the Adapter Pattern, and there are numerous examples of front end UI pattern implementations in the documentation.
Have you tried PEAR::Pager? Usage examples here.
you can try this:
Zebra_Pagination, a generic, Twitter Bootstrap compatible, pagination class written in PHP
check the link below:
http://stefangabos.ro/php-libraries/zebra-pagination
// pagination class
class Pagination
{
// database handle
private $dbh;
// total records in table
private $total_records;
// limit of items per page
private $limit;
// total number of pages needed
private $total_pages;
// first and back links
private $firstBack;
// next and last links
private $nextLast;
// where are we among all pages?
private $where;
public function __construct($dbh) {
$this->dbh = $dbh;
}
// determines the total number of records in table
public function totalRecords($query, array $params)
{
$stmt = $this->dbh->prepare($query);
$stmt->execute($params);
$this->total_records = $stmt->fetchAll(PDO::FETCH_COLUMN)[0];
if (!$this->total_records) {
echo 'No records found!';
return;
}
}
// sets limit and number of pages
public function setLimit($limit)
{
$this->limit = $limit;
// determines how many pages there will be
if (!empty($this->total_records)) {
$this->total_pages = ceil($this->total_records / $this->limit);
}
}
// determine what the current page is also, it returns the current page
public function page()
{
$pageno = (int)(isset($_GET['pageno'])) ? $_GET['pageno'] : $pageno = 1;
// out of range check
if ($pageno > $this->total_pages) {
$pageno = $this->total_pages;
} elseif ($pageno < 1) {
$pageno = 1;
}
// links
if ($pageno > 1) {
// backtrack
$prevpage = $pageno -1;
// 'first' and 'back' links
$this->firstBack = "<div class='first-back'><a href='$_SERVER[PHP_SELF]?pageno=1'>First</a> <a href='$_SERVER[PHP_SELF]?pageno=$prevpage'>Back</a></div>";
}
$this->where = "<div class='page-count'>(Page $pageno of $this->total_pages)</div>";
if ($pageno < $this->total_pages) {
// forward
$nextpage = $pageno + 1;
// 'next' and 'last' links
$this->nextLast = "<div class='next-last'><a href='$_SERVER[PHP_SELF]?pageno=$nextpage'>Next</a> <a href='$_SERVER[PHP_SELF]?pageno=$this->total_pages'>Last</a></div>";
}
return $pageno;
}
// get first and back links
public function firstBack()
{
return $this->firstBack;
}
// get next and last links
public function nextLast()
{
return $this->nextLast;
}
// get where we are among pages
public function where()
{
return $this->where;
}
}
Use:
$pagination = new Pagination($dbh);
$pagination->totalRecords('SELECT COUNT(*) FROM `photos` WHERE `user` = :user', array(':user' => $_SESSION['id']));
$pagination->setLimit(12);
$pagination->page();
echo $pagination->firstBack();
echo $pagination->where();
echo $pagination->nextLast();
Result:
<div class='first-back'><a href='/xampp/web_development/new_study_2014/imagebox2016/app/public/test.php?pageno=1'>First</a> <a href='/xampp/web_development/new_study_2014/imagebox2016/app/public/test.php?pageno=3'>Back</a></div>
<div class='page-count'>(Page 4 of 6)</div>
<div class='next-last'><a href='/xampp/web_development/new_study_2014/imagebox2016/app/public/test.php?pageno=5'>Next</a> <a href='/xampp/web_development/new_study_2014/imagebox2016/app/public/test.php?pageno=6'>Last</a></div>
public function make_pagination()
{
$total = 0;
$query = "SELECT COUNT(downloads.dn_id) FROM downloads WHERE downloads.dn_type = 'audios'";
$stmt = $this->conn->prepare($query);
$stmt->execute();
$total = $stmt->fetchColumn();
//echo 'row_count = ' . $total;
// How many items to list per page
$limit = 11;
// How many pages will there be
$pages = ceil($total / $limit);
// What page are we currently on?
$page = min($pages, filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT, array(
'options' => array(
'default' => 1,
'min_range' => 1,
),
)));
// Calculate the offset for the query
$offset = ($page - 1) * $limit;
// Some information to display to the user
$start = $offset + 1;
$end = min(($offset + $limit), $total);
// The "back" link
$prevlink = ($page > 1) ? '« ‹' : '<span class="disabled">«</span> <span class="disabled">‹</span>';
// The "forward" link
$nextlink = ($page < $pages) ? '› »' : '<span class="disabled">›</span> <span class="disabled">»</span>';
// Display the paging information
echo '<div id="paging"><p>'.$prevlink.' Page '.$page.' of '.$pages. ' pages'. $nextlink.' </p></div>';
//prepare the page query
$query2 = "
SELECT * FROM downloads, map_artists, song_artists
WHERE map_artists.dn_id = downloads.dn_id
AND song_artists.artist_id = map_artists.artist_id
AND downloads.dn_type = 'audios' GROUP BY downloads.dn_id
ORDER BY downloads.dn_time DESC LIMIT :limit OFFSET :offset ";
$stmt2 = $this->conn->prepare($query2);
$stmt2->bindParam(':limit', $limit, PDO::PARAM_INT);
$stmt2->bindParam(':offset', $offset, PDO::PARAM_INT);
$stmt2->execute();
// Do we have any results?
if ($stmt2->rowCount() > 0) {
// Define how we want to fetch the results
$stmt2->setFetchMode(PDO::FETCH_ASSOC);
$iterator = new IteratorIterator($stmt2);
// Display the results
foreach ($iterator as $row) {
echo '<p>'. $row['dn_title'].' - '. $row['artist_name'].'</p>';
}
} else {
echo '<p>No results could be displayed.</p>';
}
}
Its Very possible that your SQL SELECT statement query may 1000 result into thousand of records. But its is not good idea to display all the results on one page. So we can divide this result into many pages as per requirement as pagination Class .
PAGINATE DATA WITH PAGINATION CLASS VERY EASY
pagination Class helps to generate paging
How To Use Pagination Class
visit this link for more info
http://utlearn.com/2017/02/15/pagination-class-use-pagination-class/
<?php
/**
* #package pagination class
* #version 1.0
*/
/*
#class Name: pagination
#Author: Ahmed Mohamed
#Version: 1.0
#Author URI: https://www.fb.com/100002349977660
#Website URI: http://www.utlearn.com
#class page URI: http://utlearn.com/2017/02/15/pagination-class-use-pagination-class
*/
include_once 'libs/config.php';
include_once 'libs/Database.php';
include_once 'libs/Model.php';
include_once 'libs/pagination.php';
if(!empty($_GET["page"]) and is_numeric($_GET["page"])){
$page = htmlspecialchars(strip_tags($_GET["page"]));
} else {
$page = 1;
}
// news = table name / you page URL / current page / true or false for full query
// its false i just use table name
$pag = new pagination("news", URL."?page=", 3, $page, false);
$pagination = $pag->pagination();
$data = $pag->data();
?>
<news>
<?php foreach($data as $news){ ?>
<header><h1><?=$news->title ?></h1> | <span><?=$news->date ?></span></header>
<div>
<?=$news->content ?>
</div>
<?php } ?>
</news>
<?=$pagination ?>