We are trying to apply pagination concept on Course Category list page in our MOODLE website and we have got success in it. But while displaying it shows the same course on every page. We are able to set how much number of topics/categories should be shown on each page, and same number of categories are shown. But each page shows the same topic. Please help if somebody has applied pagination into their MOODLE website.
There is no generic way to add pagination to different pages in Moodle - there is a general '$OUTPUT->paging_bar' function, which will generate the output for a paging bar, but it is then up to your own code to decide what to do with the 'page' parameter that is then passed on to the PHP script.
Usually the code looks something like this:
$page = optional_param('page', 0, PARAM_INT);
$perpage = optional_param('perpage', 30, PARAM_INT);
...
$count = $DB->count_records_sql('Some SQL query to count the number of results');
$start = $page * $perpage;
if ($start > $count) {
$page = 0;
$start = 0;
}
$results = $DB->get_records_sql('Some SQL query to get the results', array(parameters for query), $start, $perpage); // Start at result '$start' and return '$perpage' results.
Alternatively, if this is not possible, you can get all the results and then use array_slice:
$page = optional_param('page', 0, PARAM_INT);
$perpage = optional_param('perpage', 30, PARAM_INT);
...
$results = $DB->get_records_sql('Some SQL query to get the results', array(params for query));
$start = $page * $perpage;
if ($start > count($results)) {
$page = 0;
$start = 0;
}
$results = array_slice($results, $start, $perpage, true);
The list of courses within a category are already paginated.
So I'm guessing you mean the list of categories? You can use a flexible table with pagination
http://docs.moodle.org/dev/lib/tablelib.php
You can also display one section of a course by going to course -> edit settings -> Course format -> Course Layout -> show one section per page.
But if you want to display some of the sections - not just one - then you probably need to have a look at designing a course format
http://docs.moodle.org/dev/Course_formats
Related
Im trying to create pagination using PHP but I have issue with quantity of page.
my pagination created used
foreach(range(1, $pager) as $i){
echo '<span class="pagination-num" data-pager="'.$i.'">'.$i.'</span>';
}
the problem comes when the range is too large. like on the image below. variable $pager contains a dynamic value. $pager counts how many pages should created from quantity of the content.
I set 10 content per page, so if there is 100 content:
$pager = ceil($content / 10);
it's there any way to edit pagination with dots. (next and prev I created using custom Jquery).
first of all you need to set items per page for example 10 items per page
<?php
$ipp = 10; //Item Per Page
if(isset($_GET["page"]) AND $_GET["page"] > 0){
$page_number = $_GET['page']; // page number
}
else{$page_number = 1;}
$total_items = 100; //total items
$total_pages = ceil($total_items/$ipp); //total pages
$page_position = (($page_number-1) * $ipp); //page position
?>
just in case if you are using sql:
"SELECT * FROM `table` WHERE --something-- ORDER BY `id` ASC LIMIT {$page_position}, {$ipp}"
I am working with laravel's LengthAwarePaginator Class. My problem is that I cannot use
$users = DB::table('users')->paginate(15);
or in other words,larvel's querybuilder or eloquent results. The reason is I have provided user with a frontend where they can create queries dynamically that can as simple as a select query and can be as complicated as queries with multiple joins etc. So I am left with only option of using LengthAwarePaginator. Here is what I have done do far
private function queryWithPagination($queryString,$path,$fieldName = '',$sortOrder = '',$perPage = 100){
$queryString = str_replace(''',"'",$queryString);
$queryString = str_replace('**',"",$queryString);
if(!empty($fieldName) && !empty($sortOrder)){
$queryString .= " ORDER BY '{$fieldName}' {$sortOrder}";
}
$currentPage = LengthAwarePaginator::resolveCurrentPage();
$limit = $perPage +1; // to have pagination links clickable i.e next,previous buttons
$queryString.= " LIMIT {$limit}";
if($currentPage == 1){
$queryString.= " OFFSET 0";
}
else{
$offset = ($currentPage-1)*$perPage;
$queryString.= " OFFSET {$offset}";
}
$path = preg_replace('/&page(=[^&]*)?|^page(=[^&]*)?&?/','', $path);
$result = DB::connection('database')->select($queryString);
$collection = new Collection($result);
//$currentPageSearchResults = $collection->slice(($currentPage - 1) * $perPage, $perPage)->all();
$entries = new LengthAwarePaginator($collection, count($collection), $perPage);
$entries->setPath($path);
//dd($queryString,$result);
dd($entries);
return $entries;
}
As you can see I append LIMIT and OFFSET in the query otherwise, for complex queries the load time was getting greater resulting in bad user experience. The problem with current set up is that the last page is always set to 2 and when I get to second page I cannot browse more results i.e cases where records returned were more than 500 I can still only browse upto page 2. How do I fix this issue where by using limit offset I can still keep browsing all the results until I get to the last page and then disable the pagination links?
made the second parameter to LengthAwarePaginator dynamic as follows in the given code,it solved my problem
$entries = new LengthAwarePaginator($collection, (count($collection)>=101)?$currentPage*$limit:count($collection), $perPage);
So basically, this is how my paging query looks like at the moment:
$limit = mysql_escape_string($_GET['pagenumber']);
if (empty($limit)){
$limit = "1";
}
$page = $limit * 10;
$flim1 = $page / 10;
$flim = $page - 10;
At the end of my query, I have this:
... LIMIT $flim, $page
Which should be from 1, 10 if the pagenumber is 1 and 10, 20 if the page number is 2. It works on the first page perfectly, but when I get to the second, there were 20 results, although when I echoed $flim and $page, they were 10 and 20. I cannot understand why!
I've heard about some double-query for paging. If you know a simple way to do this that is kind of like this one, please post a link. Will my method work?
Please see specification of LIMIT there is LIMIT offset,count
So in your situation it would be LIMIT $flim,10
Full code:
$page = mysql_escape_string($_GET['pagenumber']);
if (empty($limit)){
$page = "1";
}
$items_per_page=10;
$offset = ($page-1)*$_items_per_page;
Then LIMIT $offset,$items_per_page
Additionally you would need count for all items to not get above max page
I am creating a pagination script and I need to get the first and last results in the database query so that I can determine what results appear when the user clicks a page to go to. This is the code that I have at the minute:
// my database connection is opened
// this gets all of the entries in the database
$q = mysql_query("SELECT * FROM my_table ORDER BY id ASC");
$count = mysql_num_rows($q);
// this is how many results I want to display
$max = 2;
// this determines how many pages there will be
$pages = round($count/$max,0);
// this is where I think my script goes wrong
// I want to get the last result of the first page
// or the first result of the previous page
// so the query can start where the last query left off
// I've tried a few different things to get this script to work
// but I think that I need to get the first or last result of the previous page
// but I don't know how to.
$get = $_GET['p'];
$pn = $_GET['pn'];
$pq = mysql_query("SELECT * FROM my_table ORDER BY id ASC LIMIT $max OFFSET $get");
// my query results appear
if(!$pn) {
$pn = 1;
}
echo "</table><br />
Page $pn of $pages<br />";
for($p = 1;$p<=$pages;$p++) {
echo "<a href='javascript:void(0);' onclick='nextPage($max, $p);' title='Page $p'>Page $p</a> ";
}
I think you have few problems there, but I try to tackle them for you. First, as comments say above, you are using code that it vulnerable to SQL injection. Take care of that - you might want to use PDO, which is as easy use as MySQL extension, and will save you from many trouble (like injection).
But to your code, lets go through it:
You should ask DB to get count of the rows, not using mysql function, it's far more effective, so use SELECT count(*) FROM mytable.
For $pages use ceil() as you want all rows to be printed, if you have $max 5 and have 11 rows, round will make $pages 2, where you actually want 3 (last page just contains that last 11th row)
in LIMIT you want to LIMIT row_count OFFSET offset. You can calculate offset from page number, so: $max = row_count but $offset = ($max * $page) - $max. In your code if $get is directly the page, it means you get $get'th row (Not sure though what happens in your JS nextpage. Bare in mind that not all use JavaScript.)
I have prepared simple example here which uses PDO, maybe that gives you idea how simple it's use PDO.
The selecting rows shows example how to put parameters in SQL, it would be perfectly safe in this case state, 'SELECT * FROM pseudorows LIMIT '.$start.','.$max by I wanted to make an example how easy it is (and then safe):
// DB config
$DB_NAME = 'test';
$DB_USER = 'test';
$DB_PASSWD = 'test';
// make connection
try {
$DB_CONN = new PDO("mysql:host=localhost;dbname=".$DB_NAME, $DB_USER, $DB_PASSWD);
$DB_CONN->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
die($e);
}
// lets say user param 'p' is page, we cast it int, just to be safe
$page = (int) (isset($_GET['p'])?$_GET['p']:1);
// max rows in page
$max = 20;
// first select count of all rows in the table
$stmt = $DB_CONN->prepare('SELECT count(*) FROM pseudorows');
$stmt->execute();
if($value = $stmt->fetch()) {
// now we know how many pages we must print in pagination
// it's $value/$max = pages
$pages = ceil($value[0]/$max);
// now let's print this page results, we are on $page page
// we start from position max_rows_in_page * page_we_are_in - max_rows_in_page
// (as first page is 1 not 0, and rows in DB start from 0 when LIMITing)
$start = ($page * $max) - $max;
$stmt = $DB_CONN->prepare('SELECT * FROM pseudorows LIMIT :start,:max');
$stmt->bindParam(':start',$start,PDO::PARAM_INT);
$stmt->bindParam(':max', $max,PDO::PARAM_INT);
$stmt->execute();
// simply just print rows
echo '<table>';
while($row = $stmt->fetch()) {
echo '<tr><td>#'.$row['id'].'</td><td>'.$row['title'].'</td></tr>';
}
echo '</table>';
// let's show pagination
for($i=1;$i<=$pages;$i++) {
echo '[ '.$i.' ]';
}
}
mysql_fetch_array returns an associative array
Which means you can use reset and end to get the first and last results:
$pqa = mysql_fetch_array($pq);
$first = reset($pqa);
$last = end($pqa);
I don't see how you plan to use the actual results, just page numbers should be sufficient for pagination.
Still, hope it helps. And yes, upgrade to mysqli, so your code doesn't get obsolete.
Is it possible to create pagination without getting all elements of table?
But with pages in GET like /1 /666…
It usually involves issuing two queries: one to get your "slice" of the result set, and one to get the total number of records. From there, you can work out how many pages you have and build pagination accordingly.
A simply example:
<?php
$where = ""; // your WHERE clause would go in here
$batch = 10; // how many results to show at any one time
$page = (intval($_GET['page']) > 0) ? intval($_GET['page']) : 1;
$start = $page-1/$batch;
$pages = ceil($total/$batch);
$sql = "SELECT COUNT(*) AS total FROM tbl $where";
$res = mysql_query($sql);
$row = mysql_fetch_assoc($res);
$total = $row['total'];
// start pagination
$paging = '<p class="paging">Pages:';
for ($i=1; $i <= $pages; $i++) {
if ($i==$page) {
$paging.= sprintf(' <span class="current">%d</a>', $i);
} else {
$paging.= sprintf(' %1$d', $i);
}
}
$paging.= sprintf' (%d total; showing %d to %d)', $total, $start+1, min($total, $start+$batch));
And then to see your pagination links:
...
// loop over result set here
// render pagination links
echo $paging;
I hope this helps.
Yes, using mySQL's LIMIT clause. Most pagination tutorials make good examples of how to use it.
See these questions for further links and information:
How do you implement pagination in PHP?
Searching for advanced php/mysql pagination script
more results
You can use LIMIT to paginate over your result set.
SELECT * FROM comments WHERE post_id = 1 LIMIT 5, 10
where LIMIT 5 means 5 comments and 10 is the offset. You can also use the longer syntax:
... LIMIT 5 OFFSET 10