Pagination increment pages - php

A form showing different posts of user. Posts which is stored in database. Now the problem is the previous pagination works fine but the next pagination is incrementing 2 blank pages and url changes with that page. Can anyone tell me whats wrong with this code .?
php:
<?php
$limitr = ((($page*2)+1)-2)*$perpage;
$query = mysqli_query($dbc, "SELECT SQL_CALC_FOUND_ROWS * FROM final1 LIMIT {$limitr}, {$perpage}");
$records = mysqli_fetch_all($query);
$total = mysqli_query($dbc, "SELECT FOUND_ROWS() as total");
$total = mysqli_fetch_assoc($total)['total'];
$pages = ceil($total/$perpage);
?>
<?php
if($page>1){
?>
<a class="page-link" href="?page=<?php $pagep = $page -1; echo $pagep; ?>" tabindex="-1">Previous</a>
<?php
}
?>
</li>
<li class="page-item">
<?php
if($page<$pages){
?>
<a class="page-link" href="?page=<?php $pagen = $page +1; echo $pagen; ?>">Next</a>
<?php
}
?>

"SELECT SQL_CALC_FOUND_ROWS * FROM final1 LIMIT {$limitr}, {$perpage}");
The first parameter after the LIMIT the offset,, the second is how much records do you want.
But I'm not sure what are you calculating with limitr btw. If you already have which page do you want, it should be simply
LIMIT {($page-1)*perpage}, {$perpage}
Also, the database is unordered, so might miss some records or duplicate others, might wanna add some kind of ORDER BY option.
(SORRY, ORDERS ARE REVERSED WHEN USED WITH COMMA!)

Related

Open the Blog Posts by clicking on the Blog Categories

I have a blog page. I want that when a user Clicks on "All Posts", it should show all posts from Blog. And when someone clicks on a category like "Catering", it should show the posts from "Catering" category only.
Here is what i have did so far
<div class="blog-nav">
<ul class="nav">
<li><a>All Posts</a></li>
<?php
$SelectBlogcats = mysqli_query($con, "SELECT * FROM blog GROUP BY cat_blog");
while($row = mysqli_fetch_assoc($SelectBlogcats)){
$Cat_query = mysqli_query($con,"SELECT * FROM cat_blog WHERE
id=".$row['cat_blog']);
$main_cat = mysqli_fetch_assoc($Cat_query);
?>
<li><a><?php echo $main_cat['bcat_name'];?></a></li>
<?php } ?>
</ul>
</div>
Tested and working answer
<?php
$cat_id=0;
$condition="";
if(isset($_GET['cat'])){
$cat_id=$_GET['cat'];
$condition="where cat_blog=$cat_id";
}
$SelectBlogcats = mysqli_query($con, "SELECT * FROM blog GROUP BY cat_blog");
while($row = mysqli_fetch_assoc($SelectBlogcats)){
$Cat_query = mysqli_query($con,"SELECT * FROM cat_blog WHERE
id=".$row['cat_blog']);
$main_cat = mysqli_fetch_assoc($Cat_query);
?>
<li>
<h2><?php echo $main_cat['bcat_name'];?></h2>
</li>
<?php } ?>
Some semi-pseudo code which might help you accomplish your goals - wholly untested however.
The nested sql queries you have is not very efficient and it is highly likely that a simple join between the tables is what you really need.
Each hyperlink used to select a new / different category to display needs to set ( in this example ) a querystring parameter which can be used to filter records from the entire recordset.
<?php
/*
Hopefully a single query should suffice
joining the two tables rather than querying
separately.
Store the result of the query and use that to build
the nav menu and also display the content late
*/
$cat=!empty( $_GET['category'] ) ? $_GET['category'] : 'all';
# without seeing the schema this is a guess!
$sql='SELECT * FROM `blog` b
JOIN `cat_blog` cb on cb.`id`=b.`cat_blog`
GROUP BY b.`cat_blog`';
$res=$con->query( $sql );
$rs=$res->fetch_all( MYSQLI_ASSOC );
?>
With the data stored in an associative array you can proceed to generate the hyperlink menu where each link has a querystring variable set; ie: ?category=X
<div class="blog-nav">
<ul class="nav">
<li><a href='?category=all'>All Posts</a></li>
<?php
foreach( $rs as $row ){
$active = $cat==$row['bcat_name'] ? ' class="active"' : '';
printf( '
<li%2$s>
%1$s
</li>
',
$row['bcat_name'],
$active
);
}
?>
</ul>
</div>
The recordset can then be processed again to output the actual blog content paying attention to the variable $cat to dictate which records are to be displayed.
<!-- blog display - ALL records or the filtered subset -->
<div class="blog-content">
<?php
if( !empty( $rs )){
foreach( $rs as $row ){
// display only the filtered category or ALL records
if( $cat==$row['cat_name'] or $cat=='all' ){
/* output your blog content ..... */
}
}
}else{
echo 'There was an error fetching database records.';
}
$res->close();
?>
</div>

Getting only last message for each user

I am doing PM system for my site. I created subpage for each conversation by two users. I am having hard time programming the front page, where all conversations are printed. I cant get only one and last meassage for each user.
Here is my function:
public function fetch_data($id_uporabnika) {
global $pdo;
$query = $pdo->prepare("SELECT * FROM zs WHERE za = ? ORDER BY datum");
$query->bindValue(1, $id_uporabnika);
$query->execute();
return $query->fetchAll();
}
And here is my code for printing conversations:
<?php
} else {
$zs = new Zs;
$id_uporabnika = $trenutni['id'];
$zsji = $zs->fetch_data($id_uporabnika);
?>
<h2>Zasebna sporočila</h2>
<ul class="vsi-zsji">
<?php foreach ($zsji as $sporocilo): ?>
<?php $od = $oseba->fetch_data($sporocilo['od']) ?>
<li>
<a href="<?php echo $url; ?>zs/poglej/<?php echo $sporocilo['od']; ?>">
<img src="<?php echo $url; ?>inc/timthumb.php?src=<?php echo $od['slika_potem'] ?>&w=60&h=60" alt="">
<p><b><?php echo $od['uporabnisko_ime'] ?></b></p>
<p><?php echo $sporocilo['vsebina'] ?></p>
</a>
</li>
<?php endforeach ?>
</ul>
<?php } ?>
I get 10 PMs from one user, 3 for another. I want to display just the latest one.
Just put a LIMIT clause in your SQL query and order by DESC to get the latest message:
$query = $pdo->prepare("SELECT * FROM zs WHERE za = ? ORDER BY datum DESC LIMIT 1");
something like this should help
SELECT id,datum, max(pm) FROM zs WHERE za = ? group by id,datum

MySQL Query pagination with PHP

How can i add a pagination system to this simple item display? And how i can add pagination for the results from filter? I just get lost that part and i cant figure it out!
I want to apply CSS on the menu too!
Here's the code:
<?php
include('db.php');
if(isset($_POST['filter']))
{
$filter = $_POST['filter'];
$result = mysql_query("SELECT * FROM products where Product like '%$filter%' or Description like '%$filter%' or Category like '%$filter%'");
}
else
{
$result = mysql_query("SELECT * FROM products");
}
while($row=mysql_fetch_assoc($result))
{
echo '<li class="portfolio-item2" data-id="id-0" data-type="cat-item-4">';
echo '<div>
<span class="image-block">
<a class="example-image-link" href="reservation/img/products/'.$row['imgUrl'].'" data-lightbox="example-set" title="'.$row['Product'].'""><img width="225" height="140" src="reservation/img/products/'.$row['imgUrl'].'" alt="'.$row['Product'].'" title="'.$row['Product'].'" />
</a>
</span>
<div class="home-portfolio-text">
<h2 class="post-title-portfolio"><font color="#666666">'.$row['Product'].'</font></h2>
<p class="post-subtitle-portfolio"><font color="#666666">Descrição: '.$row['Description'].'
<p class="post-subtitle-portfolio"><font color="#666666">Categoria: '.$row['Category'].'
<p class="post-subtitle-portfolio">Código: '.$row['Price'].'</p><br/></font></p>
</div>
</div>';
echo '</li>';
}
?>
EDITED:
<?php
include('db.php');
if(isset($_POST['filter']))
{
$filter = $_POST['filter'];
$result = mysql_query("SELECT * FROM products where Product like '%$filter%' or Description like '%$filter%' or Category like '%$filter%'");
}
else
{
$start=0;
$limit=6;
if(isset($_GET['id']))
{
$id = $_GET['id'];
$start = ($id-1)*$limit;
}
$result = mysql_query("SELECT * FROM products LIMIT $start, $limit");
}
while($row = mysql_fetch_array($result))
{
echo '<li class="portfolio-item2" data-id="id-0" data-type="cat-item-4">';
echo '<div>
<span class="image-block">
<a class="example-image-link" href="reservation/img/products/'.$row['imgUrl'].'" data-lightbox="example-set" title="'.$row['Product'].'""><img width="225" height="140" src="reservation/img/products/'.$row['imgUrl'].'" alt="'.$row['Product'].'" title="'.$row['Product'].'" />
</a>
</span>
<div class="home-portfolio-text">
<h2 class="post-title-portfolio"><font color="#666666">'.$row['Product'].'</font></h2>
<p class="post-subtitle-portfolio"><font color="#666666">Descrição: '.$row['Description'].'
<p class="post-subtitle-portfolio"><font color="#666666">Categoria: '.$row['Category'].'
<p class="post-subtitle-portfolio">Código: '.$row['Price'].'</p><br/></font></p>
</div>
</div>';
echo '</li>';
}
echo "</ul>";
$rows = mysql_num_rows(mysql_query("SELECT * FROM products"));
$total = ceil($rows/$limit);
if($id>1)
{
echo "<center><a href='?id=".($id-1)."' class='button'>Anterior</a></center>";
}
if($id!=$total)
{
echo "<center><a href='?id=".($id+1)."' class='button'>Próximo</a></center>";
}
?>
You should have something like this:
// declare a base query
$q = "SELECT * FROM products";
if(isset($_POST['filter']))
{
$filter = $_POST['filter'];
// append filter to query
$q += "where Product like '%$filter%' or Description like '%$filter%' or Category like '%$filter%'");
}
// check for "page" URL parameter, if not available, go to first page
$page = isset($_GET['page']) ? $_GET['page'] : 1;
// check for "pageSize" URL parameter, if not available, fall back to 20
$pageSize = isset($_GET['pageSize']) ? $_GET['pageSize'] : 20;
// append the pagination to your query
$q += sprintf("LIMIT %d,%d;", ($page-1)*$pageSize, $pageSize);
// execute the constructed query
$result = mysql_query($q);
Note that the code is "pseudoish", not tested, but should give you the base idea.
Also, you can check this SO post about pagination with MySQL.
UPDATE
In PHP if you use an uninitialized variable, then it will have a context-dependent default value. See the documentation about this here. Here is an extract:
It is not necessary to initialize variables in PHP however it is a
very good practice. Uninitialized variables have a default value of
their type depending on the context in which they are used - booleans
default to FALSE, integers and floats default to zero, strings (e.g.
used in echo) are set as an empty string and arrays become to an empty
array.

Paginating MySql Results

I have a table that pulls tickets from a MYSQL database and displays them to the user. This part works wonderfully! But, once the user gets 5-10 tickets, the page becomes long and ugly. I am wanting to paginate the responses automatically to show maybe 5 tickets per page and show the rest on following pages.
I am using Bootstrap and have the following for the display of the pagination. "Although I fear this is only pseudo code" I added id's to each main element.
<ul class="pager" id="pagerUL">
<li class="previous" id="previousUL">
← Previous
</li>
<li class="next" id="nextUL">
Next →
</li>
</ul>
Essentially the only code used to pull the database information on the page is:
<?php if(count($tickets) > 0) : ?>
<?php foreach ($tickets as $ticket): ?>
//table content
<?php endforeach ?>
<?php else : ?>
<tr>
<td colspan="7">No Tickets Created.</td>
</tr>
<?php endif; ?>
I thought we could add something to the <?php if(count($tickets) > 0) : ?> But honestly, I am not sure as I am not a expert at php and never even attempted or had the need to build pagination up until now. Any help, guidance, thoughts would be appreciated.
Pass the page number thru the URL and then grab it via php with $_GET.
$page = $_GET['page'];
$per_page = 10; // Define it as you please
$start = $page*$per_page;
$query = "SELECT * FROM table LIMIT ".$start.", ".$per_page;
$result = mysql_query($query);
$count = mysql_num_rows($result);
$i = 0;
for($i=0;$i<$count;$i++)
{
//echo out what you want
echo "";
}
$total_pages = ceil($count/$per_page);
for($i=0;$i<$total_pages;$i++)
{
if($page != $i)
{
echo "<a href='/page.php?page=".$i."'>".$i."</a>";
} else
{
echo $i;
}
}

Basic pagination

I am not a well-versed programmer so i don't want to use a complicated pagination. Is there an alternative to using a pagination like in my queries can i limit them to say 20 results and then if their are more than 20 results i can show a "next" button and then that button will further load the next results??
I only want "next" to show if there are 20> results? Any help will be appreciated. Thanks.
Code:
$query="SELECT * FROM actresses where actress_id = '$actressid' and production_full_name LIKE '%$q%'";
$result=mysql_query($query);
$num=mysql_numrows($result);
mysql_close();
echo "";
$i=0;
while ($i < $num) {
$1=mysql_result($result,$i,"production_full_name");
$2=mysql_result($result,$i,"production_id");
$3=mysql_result($result,$i,"actress");
echo "<br><div id=linkcontain><a id=slink href=$data/actress.php?id=$2>$3</a><div id=production>$1</div></div>";
echo "";
$i++;
}
You could add a limit to your query.
$lower_limit = $results_per_page * $page_number;
$upper_limit = $lower_limit + $results_per_page
..and production_full_name LIKE '%$q%' LIMIT $lower_limit, $upper_limit
Then make a conditional "next page" link
if ($upper_limit > 20) echo 'Next;
You can find many examples searching on google.
http://www.php-mysql-tutorial.com/wikis/php-tutorial/paging-using-php.aspx for example.
You only have to edit $rowsPerPage for amount of results, and if you want further edit on what to get from the DB, the $query.
Includes are not necessary, though.
edit: note the implication of using a $_GET that will have influence on the DB query. You have to be careful to not allow dangerous values in it (mysql injection). In the example of the webpage, it uses ceil, so I believe that it will output 0 for a non numeric value, which is safer.
You can use the PEAR packages.
They are much easier to use similar to the frameworks.
But before you use them you need to check whether the PEAR works on your server or not.
If you are using it locally then there are steps to install the PEAR packages on your local machine. For more instructions to install PEAR.
Click here to view the installation steps.
Once you have installed the PEAR package please follow the instruction to configure the PAGER class.http://www.codediesel.com/php/simple-pagination-in-php/
J
Something like that:
$data = mysql_query("SELECT * FROM `table`");
$total_data = mysql_num_rows($data);
$step = 30;
$from = $_GET['p'];
$data = mysql_query("SELECT * FROM `table` LIMIT '.$from.','.$step.'"
And creating links:
$p=1;
for ($j = 0 ; $j <= $total_data+$step; $j+=$step)
{
echo ' '.$p.' ';
$p++;
} ?>
Not tested.
If your query is set up as
"SELECT SQL_CALC_FOUND_ROWS * FROM actresses where actress_id = '$actressid' and production_full_name LIKE '%$q%' LIMIT ".($page*$lpage).",".$lpage
... the next statement can be SELECT FOUND_ROWS() to get the actual number of results.
Don't forget to put mysql_real_escape_string() on those variables.
NEVER use SELECT * with mysql_num_rows; if it's a big table, it will waste a LOT of time.
What you can do is fetch a COUNT(*) of how many rows are in your set of data. Then decide how many items you want per page. $numberOfRows / $itemsPerPage gives you the number of pages. In MySQL, to limit results you use LIMIT X, Y X is the beginning of the range, and Y is the number of items you want to fetch. So to fetch all the items on a page, your query would be LIMIT ($currentPage * $itemsPerPage), $itemsPerPage Then it's up to you, depending on how you want to format your pagination, to write the view logic. Just go from back to front: if the current page is 1, then the previous button is disabled. If the page is not 1, then the current page number is the number of pages from the beginning. If the total number of pages is bigger than the current page, then count from the current page, until the last page (unless you want to cut off the page count at some point)
I use the following method to assist in creating a list of pages, no matter what direction. I could plug in 5 for the current page, and 0 as the goal page, and it would return a list of 5 pages for me to iterate through, in order.
/*
* Generates a list of pages based on the current page to the goal page number
*/
function generatePageList($currentPage, $goal) {
$span = $goal - $currentPage;
$step = abs($span) / $span;
$list = array();
for($x = $currentPage; $x !== $goal;) {
// We want to add the step at the beginning of the loop, instead of
// at the end
// Fixes bug when there are only two pages
$x += $step;
$list[] = $x;
}
return $list;
}
This is more easy way to create pagination of a data
<?php
require_once 'db_connect.php';
$limit = 20;
if (isset($_GET["page"])) { $page = $_GET["page"]; } else { $page=1; };
$start_from = ($page-1) * $limit;
$sql = "SELECT * FROM employee ORDER BY id ASC LIMIT $start_from, $limit";
$rs_result = mysqli_query($con, $sql);
?>
<table class="table table-bordered">
<thead>
<tr>
<th>Name</th>
<th>Salary</th>
<th>Age</th>
</tr>
</thead>
<tbody>
<?php
while ($row = mysqli_fetch_assoc($rs_result)) {?>
<tr>
<td><?php echo $row["employee_name"]; ?></td>
<td><?php echo $row["employee_salary"]; ?></td>
<td><?php echo $row["employee_age"]; ?></td>
</tr>
<?php
};
?>
</tbody>
</table>
<?php
$sql = "SELECT COUNT(id) FROM employee";
$rs_result = mysqli_query($con, $sql);
$row = mysqli_fetch_row($rs_result);
$total_records = $row[0];
$total_pages = ceil($total_records / $limit);
$pagLink = "<nav><ul class='pagination'>";
for ($i=1; $i<=$total_pages; $i++){
$pagLink .= "<li><a href='index.php?page=".$i."'>".$i."</a></li>";
};
echo $pagLink . "</ul></nav>";
?>
<script type="text/javascript">
$(document).ready(function(){
$('.pagination').pagination({
items: <?php echo $total_records;?>,
itemsOnPage: <?php echo $limit;?>,
cssStyle: 'light-theme',
currentPage : <?php echo $page;?>,
hrefTextPrefix : 'index.php?page='
});
});
</script>

Categories