I have a problem with my pagination, I need your help please.
I have 53 records but with this pagination, I can get 50 records only, I can't see the 3 others
I want to change this code to get all records please, and if I want to make the pagination easy to navigate for big records. Like this (for exp):
<< 1 2 3 4 5 ...... 184 185 >>
Thanks
<?php
include("db.php"); //include config file
//sanitize post value
$page_number = filter_var($_POST["page"], FILTER_SANITIZE_NUMBER_INT, FILTER_FLAG_STRIP_HIGH);
//validate page number is really numaric
if(!is_numeric($page_number)){die('Invalid page number!');}
//get current starting point of records
$position = ($page_number * $item_per_page);
//Limit our results within a specified range.
$results = mysqli_query($db,"SELECT id,name,message FROM paginate ORDER BY id ASC LIMIT $position, $item_per_page");
//output results from database
while($row = mysqli_fetch_array($results))
{
echo' <ul class="page_result">
<li class="page_result_img"><img src="images/pic1.jpg" class="img-responsive" alt=""/></li>
<li class="page_result_desc" id="item_'.$row["id"].'">
<h3>'.$row["id"].'.'.$row["name"].'</h3>
<p>'.$row["message"].'</p>
</li>
<p class="no">'.$row["id"].'<br><span>projet</span></p>
<div class="clearfix"> </div>
</ul>';
}
?>
projet.php
<?php
include("db.php");
$results = mysqli_query($db,"SELECT COUNT(*) FROM paginate");
$get_total_rows = mysqli_fetch_array($results); //total records
//break total records into pages
$pages = ceil($get_total_rows[0]/$item_per_page);
//create pagination
if($pages > 1)
{
$pagination = '';
$pagination .= '<ul class="paginate">';
for($i = 1; $i<$pages; $i++)
{
$pagination .= '<li>'.$i.'</li>';
}
$pagination .= '</ul>';
}
?>
.
.
.
.
<div class="approach" id="app">
<div class="container">
<div class="gallery-head text-center">
<h3>Nos projets</h3>
<p>Trouvez ici tout les projets</p>
<span> </span>
</div>
<ul id="results"></div>
<?php echo $pagination; ?>
</div>
</div>
For correct LIMIT in SQL query must be value of $page_number for the first page equal to 0. But your pagination starts from 1. Then you never get $position = 0 and SQL query skips first $item_per_page records.
Try modify $position calculation:
$position = (($page_number - 1) * $item_per_page);
Second problem is in projet.php. For 53 records (and $item_per_page = 10) is value of $pages = 6. But for cycle stops on 5. It should be:
for($i = 1; $i <= $pages; $i++)
I like to work this way .. So try this code hope it help
$results = mysqli_query($db,"SELECT * FROM paginate");
$get_total_rows = mysqli_num_rows($results); //total records
$item_per_page = 10;
//break total records into pages
$pages = ceil($get_total_rows/$item_per_page);
//create pagination
if($pages > 1)
{
?>
<ul class="paginate">
<?php
for($i = 1; $i<$pages; $i++)
{
if($pages <= 5){
?>
<li><?php echo $i; ?></li>
<?php
}elseif($pages >= $pages - 5){
?>
<li><?php echo $i; ?></li>
<?php
}
}
?>
</ul>
<?php
}
Related
I have a table of category, I want to show category data into 4 equal bootstraps 4 rows dynamically, and data must be shown in alphabetically order.
First I am counting the number of data and dividing by 4 then run 4 queries to find the first 25 data and in the second query next 25 data and so on, but looking for a better solution.
$catCount = Category::all()->count();
$inOneRow = intval( $catCount / 4);
What I want
Assuming Category is a table of category names - you can select ALL categories at once and use the ORDER BY clause on the query:
$query = 'SELECT name FROM db.categories ORDER BY name ASC;';
You can alternatively use sort on the result-set:
$query = 'SELECT name FROM db.categories;';
/* execute query here... */
sort($resultSet);
Let's assume you did this, the styling would be easy using bootstrap grid (notice mock result-set in fiddles):
<?php
const NUM_COLS = 4;
$numResults = count($dummyResult);
$numPerCol = round($numResults / NUM_COLS);
?>
<div class="container">
<div class="row">
<?php
for($i = 0, $col = 0; $col < NUM_COLS; $col++){
echo '<div class="col">';
for($colLimit = min($numResults, $i + $numPerCol); $i < $colLimit; $i++){
echo '<div class="row">'.$dummyResult[$i]['category'].'</div>';
}
echo '</div>';
}
?>
</div>
</div>
Here is a fiddle
Easier to understand, albeit probably slower example:
<?php
const NUM_COLS = 4;
$numResults = count($dummyResult);
$numPerCol = round($numResults / NUM_COLS);
?>
<div class="container">
<div class="row">
<?php
for($i = 0; $i < NUM_COLS; $i++){
echo '<div class="col">';
foreach( array_splice($dummyResult, 0, $numPerCol) as $row ){
echo '<div class="col">'.$row['category'].'</div>';
}
echo '</div>';
}
?>
</div>
</div>
Here is a fiddle
Note: Container will be 100% width of it's parent, unless styled otherwise.
Column widths will be equal by default. See Bootstrap Grid.
I am working on creating a drop down button that lets one select the year from a list of options in order to sort through a data table. The code (reproduced below) keeps repeating the last year available, I can't seem to figure out why it is doing this. I am using PHP to pull from a MySql database.
<div class="dropdown">
<button onclick="myFunction()" class="dropbtn">Select Year</button>
<div id="myDropdown" class="dropdown-content">
<?php
$year = array();
while($subject = mysqli_fetch_assoc($subject_set)) {
$i=0;
$exists = 0;
$n = count($year);
while($i < $n){
if ($subject['year'] == $year[$i]){
$exists = 1;
}
$i++;
}
if($exists == 0){
$year[$n] = $subject['year'];
echo " {$subject['year']} ";
}
}
$subject_set = find_all_subjects();
?>
</div>
</div>
Pagination PHP code:
<?php
//Connecting To The DB And Fetching Number Of Rows.
$stmt = $pdo->prepare('SELECT * FROM locations');
$stmt->execute();
$count = $stmt->rowCount();
$values = $stmt->fetchAll();
//Check If Page Number Is Set To Specific Value.
if (isset($_GET['pageno']))
{
$pageno = $_GET['pageno']; //Current Page Number.
$no_of_records_per_page = 100; // Number Of Rows Per Page.
$total_pages = ceil($count / $no_of_records_per_page); //Total Number Of Pages.
$offset = ($pageno-1) * $no_of_records_per_page; //Starting From.
}
//If Page Number Not Specified The First Page Will Be Shown.
else
{
$pageno = 1;
}
?>
HTML code beneath it:
<ul class="pagination">
//First Page.
<li>
First
</li>
//Previous Page.
<li>
Prev
</li>
<li>
//Loop Through Pages.
<?php
for ($i=1; $i <= $total_pages ; $i++)
{
echo ''.$i.'';
}
?>
</li>
//Next Page.
<li>
Next
</li>
//Last Page.
<li>
Last
</li>
It's showing all the pages:
First Previous 1 2 3 4 5 6 7 8 Next Last
But if there are many pages it would be missed up.
I want to show specific number of pages like 5 or 6:
First Previous 1 2 3 4 5 .. .. 8 Next Last
Is it possible ? Is there is a library / plugin for that?
Best use Data tables which will process the data server side, which will be your ajax call and data will load on click on next or on pagination. it will reduce the load of getting data at one go and you do not have to write separate code for the pagination too.
Refer below link.
https://datatables.net/examples/data_sources/server_side.html
Hope it will help you.
Depending on what you want displayed for the "extra" page number, change what is echoed in the if statement:
//Loop Through Pages.
<?php
for ($i=1; $i <= $total_pages ; $i++)
{
if($total_pages > 8 && $i > 6 && $i < $total_pages) {
echo '..';
} else {
echo ''.$i.'';
}
}
?>
I'm using the following code to apply a pagination to a large table in my database. It works fine however I can't figure out how to apply a WHERE Week="?" (52 weeks in the table) in the SELECT Query with the $start $limit variables. That way when I hit PREVIOUS or NEXT buttons it goes to the previous or next week of rows in that week.
<div id="content">
<?php
include("dbconfig.php");
$start=0;
$limit=10;
if(isset($_GET['id']))
{
$id=$_GET['id'];
$start=($id-1)*$limit;
}
else{
$id=1;
}
//Fetch from database first 10 items which is its limit. For that when
page open you can see first 10 items.
$query=mysqli_query($dbconfig,"select * from user LIMIT $start, $limit");
?>
<ul>
<?php
//print 10 items
while($result=mysqli_fetch_array($query))
{
echo "<li>".$result['username']."</li>";
}
?>
</ul>
<?php
//fetch all the data from database.
$rows=mysqli_num_rows(mysqli_query($dbconfig,"select * from user"));
//calculate total page number for the given table in the database
$total=ceil($rows/$limit);
if($id>1)
{
//Go to previous page to show previous 10 items. If its in page 1 then it is inactive
echo "<a href='?id=".($id-1)."' class='button'>PREVIOUS</a>";
}
if($id!=$total)
{
////Go to previous page to show next 10 items.
echo "<a href='?id=".($id+1)."' class='button'>NEXT</a>";
}
?>
<ul class='page'>
<?php
//show all the page link with page number. When click on these numbers go to particular page.
for($i=1;$i<=$total;$i++)
{
if($i==$id) { echo "<li class='current'>".$i."</li>"; }
else { echo "<li><a href='?id=".$i."'>".$i."</a></li>"; }
}
?>
</ul>
</div>
Your probably looking for a select box for the weeks, then use that value in your where clause.
<select name="weeks">
<?php
for( $i = 1; $i <= 52; $i++ ):
echo '<option name="week" value="'.$i.'"></option>';
endfor;
?>
</select>
The query:
$mysqli = dbConnect();
$stmt = $mysqli->prepare( $sql );
if( !empty( $_POST['weeks'] ) ):
$week = $_POST['week'];
// Validate the data
$week = trim( $week );
$week = htmlspecialchars( $week );
if( !ctype_digit( $week ) ):
echo 'Week is not a valid input';
else:
// Prepared statement
$sql = "SELECT * FROM user WHERE week = ? LIMIT ?, ?";
$stmt->bind_param("iii", $week, $start, $limit);
endif;
else:
$sql = "SELECT * FROM user LIMIT ?, ?";
$stmt->bind_param("ii", $start, $limit);
endif;
$stmt->execute();
$stmt->bind_result(yourparamshere);
$stmt->close();
$mysqli->close();
Note:
Please take a look at http://php.net/manual/en/pdo.prepared-statements.php
Prepared statements and stored procedures are much saver and will make you a better programmer.
hello i want to list contents as 10 contents per page
this is source code for each content
<?
while ($arama=mysql_fetch_array($arama_sonuc)) {
?>
<h4><?=$arama[baslik]?></h4>
<div class="article box">
<div class="article-desc-oku">
<p class="info">Yayınlanma: <strong><?=$arama[eklemetarihi]?></strong><br />
Yazan: <strong>Ronnie C. Lynwood</strong><br /><?=$arama[tiklanma]?> kez okunmuş.<br />
<?php rating_form("$arama[id]"); ?>
</p>
</div>
<?=$arama[spot]?>
</div> <!-- /article -->
I think you should better use a paging class rather than creating your own. This will save a lot of time of yours in next projects too. Your current problem will also be solved. Check this out.
Download Location
It looks like you are using MySQL: You can build a query using the SQL LIMIT command.
For example:
SELECT * FROM myTable LIMIT 5, 10
Will tell MySQL to return only the first ten elements after the 5th row. You can use a parameter on the query string to build an appropriate SQL query to "ask" the database which "page" you want to see.
Here http://php.about.com/od/phpwithmysql/ss/php_pagination.htm you can find a complete code example on pagination. It's also explained very well.
Sorry but I can't offer more just by seeing a snipped of code ...
i used codes below to make pagination
<?
if (isset($_GET['sayfa'])) {
$pageno = $_GET['sayfa'];
} else {
$pageno = 1;
} // if
$query = mysql_query("SELECT count(id) FROM yazilar");
$query_data = mysql_fetch_row($query);
$numrows = $query_data[0];
$rows_per_page = 10;
$lastpage = ceil($numrows/$rows_per_page);
$pageno = (int)$pageno;
if ($pageno > $lastpage) {
$pageno = $lastpage;
} // if
if ($pageno < 1) {
$pageno = 1;
} // if
$limit = 'ORDER BY id DESC LIMIT ' .($pageno - 1) * $rows_per_page .',' .$rows_per_page;
$query = mysql_query("SELECT * FROM yazilar $limit");
if ($pageno == 1) {
echo " İLK ÖNCEKİ ";
} else {
echo " <a href='{$_SERVER['PHP_SELF']}?sayfa=1'>İLK</a> ";
$prevpage = $pageno-1;
echo " <a href='{$_SERVER['PHP_SELF']}?sayfa=$prevpage'>ÖNCEKİ</a> ";
} // if
echo " ( Sayfa $pageno ) ";
if ($pageno == $lastpage) {
echo " SONRAKİ SON ";
} else {
$nextpage = $pageno+1;
echo " <a href='{$_SERVER['PHP_SELF']}?sayfa=$nextpage'>İLERİ</a> ";
echo " <a href='{$_SERVER['PHP_SELF']}?sayfa=$lastpage'>SON</a> ";
} // if
?>
Let me suggest some existing PHP solutions
Zend_Paginator, loosely coupled can be used stand alone without the whole framework.
If you want to build your own flavour I recommand the SPL countable and Iterator classes.