How can I merge this code together to get working pagination? - php

I have two sets of code for a blog type website. One shows the list of articles and the other is for a pagination. I can't figure out how to get the pagination and article list code working together. The article list code works to generate the information needed from a SQL Database for my website. However, I have no clue what needs to be changed so that it will respond to the pagination code. The pagination will generate, though the current page does not show as a button.
Article List:
<?php
include ('database-connect.php');
include ('database-query-topic2.php');
// this runs the query
// needs to have the mysql connection info passed as $con
// the second argument is the number of articles to return
$articles = list_articles($con, 5); //
// if articles are found
if ($articles) {
while ($row = mysqli_fetch_row($articles)){
?>
<!-- loop here for articles -->
<div class="article-list-item-info">
<div class="a-l-i-i-left">
<h2 class="article-title">
<?php print( $row[1]); ?>
</h2>
<div class="article-list-preview">
<?php print($row[3]); ?>
</div>
<div class="article-list-author-date">
<address class="article-list-author">
<?php print($row[4]); ?>
</address>
<time class="article-list-date"> <?php print($row[8]); ?> </time>
</div>
</div>
<img class="article-image" src=<?php print($row[6]); ?> >
</div>
<!-- end loop for articles -->
<?php
}
}
// Closing the connection
mysqli_close($con);
?>
<div class="a-l-l-m-b-container">
<?php include ("article-pagination.php"); ?>
<!--<button class="a-l-load-more-button">Load More</button>-->
</div>
database-connect.php:
<?php
$servername = "ip address";
$username = "user";
$password = "password";
$dbname = "database name";
// Create Connection
$con = mysqli_connect('ip address', 'user', 'password', 'database name');
?>
database-query-topic2.php:
<?php
//gets list of articles
// $con is the sql connection
// $limit is the number of articles to return
function list_articles($con, $limit){
// Executing the multi query
$query =
"SELECT * FROM table
WHERE article_category='category'
ORDER BY article_id DESC LIMIT $limit";
$result = mysqli_query($con, $query);
return $result;
}
article-pagination.php:
<?php
include("database-connect.php");
$query=mysqli_query($con,"select count(article_id) from `table`");
$row = mysqli_fetch_row($query);
$rows = $row[0];
$page_rows = 5; //
$last = ceil($rows/$page_rows);
if($last < 1){
$last = 1;
}
$pagenum = 1;
if(isset($_GET['pn'])){
$pagenum = preg_replace('#[^0-9]#', '', $_GET['pn']);
}
if ($pagenum < 1) {
$pagenum = 1;
}
else if ($pagenum > $last) {
$pagenum = $last;
}
//
$limit = 'LIMIT ' .($pagenum - 1) * $page_rows .',' .$page_rows;
$nquery=mysqli_query($con,"SELECT * FROM table
WHERE article_category='category'
ORDER BY article_id DESC LIMIT $limit");
//
$paginationCtrls = '';
$paginationCtrls .= '<nav aria-label="Page navigation example">';
$paginationCtrls .= '<ul class="pagination">';
if($last != 1){
if ($pagenum > 1) {
$previous = $pagenum - 1;
$paginationCtrls .= '<li class="page-item">Previous</li> ';
for($i = $pagenum-4; $i < $pagenum; $i++){
if($i > 0){
$paginationCtrls .= '<li class="page-item">'.$i.'</li> ';
}
}
}
$paginationCtrls .= ''.$pagenum.' ';
for($i = $pagenum+1; $i <= $last; $i++){
$paginationCtrls .= ' <li class="page-item">'.$i.'</li> ';
if($i >= $pagenum+4){
break;
}
}
if ($pagenum != $last) {
$next = $pagenum + 1;
$paginationCtrls .= ' <li class="page-item">Next</li> ';
}
}
echo $paginationCtrls;
'</ul>';
'</nav>';
?>

Looks like here is error
$limit = 'LIMIT ' .($pagenum - 1) * $page_rows .',' .$page_rows;
$nquery=mysqli_query($con,"SELECT * FROM table
WHERE article_category='category'
ORDER BY article_id DESC LIMIT $limit");
You are using LIMIT two times
First in $limit = 'LIMIT ....'
And second
DESC LIMIT $limit"

Related

Detect Previous Next ID

I have a little script that have a Previous & Next button.
My problem is I want to detect & place the ID in those buttons
this is the code from the pagination
<body>
<?php include_once 'data.php'; ?>
<center>
<ul class="pagination">
<?php
if($page_counter == 0){
echo "<li><a href=?start='0' class='active'>0</a></li>";
for($j=1; $j < $paginations; $j++) {
echo "";
}
}else{
echo "<a href=?start=$previous><button>Previous</button></a>";
for($j=0; $j < $paginations; $j++) {
if($j == $page_counter) {
echo " ";
}else{
echo " ";
}
}if($j != $page_counter+1)
echo "<a href=?start=$next><button>Next</button></a>";
}
?>
</ul>
</center>
In this part I have the ID but the problem is I can`t get it with this example to place it into the pagination.
<?php
foreach($result as $row) {
echo '
<div class="card"><button1>
'. $row['notice_id'] .'
<div class="time-left">
<div class="dropdown1">
' ;
}
}
else {
echo '';
}
$conn->close();
?>
</div></div>
This is the code from data.php I think I need to place some code into for detection from the ID
<?php
//include configuration file
require 'configuration.php';
$start = 0; $per_page = 1;
$page_counter = 0;
$next = $page_counter + 1;
$previous = $page_counter - 1;
if(isset($_GET['start'])){
$start = $_GET['start'];
$page_counter = $_GET['start'];
$start = $start * $per_page;
$next = $page_counter + 1;
$previous = $page_counter - 1;
}
// query to get messages from messages table
$q = "SELECT * FROM group_notice LIMIT $start, $per_page";
$query = $db->prepare($q);
$query->execute();
if($query->rowCount() > 0){
$result = $query->fetchAll(PDO::FETCH_ASSOC);
}
// count total number of rows in students table
$count_query = "SELECT * FROM group_notice";
$query = $db->prepare($count_query);
$query->execute();
$count = $query->rowCount();
// calculate the pagination number by dividing total number of rows with per page.
$paginations = ceil($count / $per_page);
?>
You can use some formulas for calculate limit and offset of results.
For example you have 100 records, and you want to paginate it into 10 records per page, and the formula is like below.
// Get Page from Query String
$page = 1;
if(!empty($_GET["page"])){
$page = $_GET["page"];
}
// Get record count
$count_query = "SELECT * FROM group_notice";
$query = $db->prepare($count_query);
$query->execute();
$count = $query->rowCount();
$per_page = 10; // records per page
$pages = ceil($count/$per_page); // get total page
$start = $page * $per_page - $per_page; // get offset
// Do something with your records
$query = db->prepare("SELECT * FROM group_notice LIMIT ?, ?");
$query->bind_param("ii", $start, $per_page); // you should use bind param if you use prepared statement
$query->execute();
if($query->rowCount() > 0){
$result = $query->fetchAll(PDO::FETCH_ASSOC);
}
if($page > 1){
echo 'Prev'; // Print Prev Page
}
for($i = 1; $i <= $pages){
echo ''.$i.''; // Print Page Number
}
if($page < $pages){
echo 'Next'; // Print Next Page
}
Hope it helps.

Php search code with pagination(Using php) is not producing the navigation links because of a warning. How do i correct the error?

Am new to php programming and I have written my php code to search data from database then displays it with pagination links for easy navigation in the event that the search result will be too many. But the pagination links will not show because of the above warning. The query is not producing the Count result to make my $limit variable true thereby displaying the first page only. This is the code below, Please can you help me correct the error so that the pagination links show.
<?php
include_once("dbconnect.php");
if(isset($_GET["search"]))
{
$condition = '';
$search_query = explode(" ", $_GET["search"]);
foreach($search_query as $text)
{
$condition .= "search LIKE '%".mysqli_real_escape_string($dbconnect, $text)."%' OR ";
}
$sql = "SELECT COUNT(stockID) FROM stock WHERE search LIKE ". $condition ."GROUP BY stockID";
$query = mysqli_query($dbconnect, $sql);
$row = mysqli_fetch_row($query);
$rows = $row[0];
$page_rows = 12;
$last = ceil($rows/$page_rows);
if($last < 1){
$last = 1;
}
$pagenum = 1;
if(isset($_GET['pn'])){
$pagenum = preg_replace('#[^0-9]#', '', $_GET['pn']);
}
if ($pagenum < 1) {
$pagenum = 1;
} else if ($pagenum > $last) {
$pagenum = $last;
}
$limit = 'LIMIT ' .($pagenum - 1) * $page_rows .',' .$page_rows;
$condition = '';
$search_query = explode(" ", $_GET["search"]);
foreach($search_query as $text)
{
$condition .= "search LIKE
'%".mysqli_real_escape_string($dbconnect, $text)."%' OR ";
}
$condition = substr($condition, 0, -4);
$sql= "SELECT * FROM stock WHERE " . $condition."
ORDER BY stockID ASC $limit";
$query = mysqli_query($dbconnect, $sql);
$textline1 = "(<b>$rows</b>)";
$textline2 = "Page <b>$pagenum</b> of <b>$last</b>";
$paginationCtrls = '';
$search_query = $_GET['search'];
if($last != 1){
if ($pagenum > 1) {
$previous = $pagenum - 1;
$paginationCtrls .= '<a href="'.$_SERVER['PHP_SELF'].'?
pn='.$previous.'&search='.$search_query.'">Previous</a> ';
for($i = $pagenum-4; $i < $pagenum; $i++){
if($i > 0){
$paginationCtrls .= '<a href="'.$_SERVER['PHP_SELF'].'?
pn='.$i.'">'.$i.'</a> ';
}
}
}
$paginationCtrls .= ''.$pagenum.' ';
for($i = $pagenum+1; $i <= $last; $i++){
$paginationCtrls .= '<a href="'.$_SERVER['PHP_SELF'].'?
pn='.$i.'&search='.$search_query.'">'.$i.'</a> ';
if($i >= $pagenum+4){
break;
}
}
if ($pagenum != $last) {
$next = $pagenum + 1;
$paginationCtrls .= ' <a href="'.$_SERVER['PHP_SELF'].'?
pn='.$next.'&search='.$search_query.'">Next</a> ';
}
}
$list = '';
$lists = '';
while($row = mysqli_fetch_array($query)){
$id = $row["stockID"];
$name = $row["stockName"];
$image = $row["thumbnail"];
$description = $row["description"];
$topline = $row['topline'];
$lists .= '<div class="col-md-3" style="margin-bottom:10px;">
<div class="panel panel-info"><a href="index.php?
page=item&stockID='.$id.'&sub_category=">
<div class="panel-body">
<img class="img-responsive" style="height:100px;"
src="resources/stocks_images/'.$image.'" />
</div>
<div class="panel-footer" style="height:100px;">'.$name.'
</div></a>
</div>
</div>';
}
}
mysqli_close($dbconnect);
?>
$dbconnect is undefined in your script. Also rewrite your query:
$sql = "SELECT COUNT(stockID) FROM stock WHERE search LIKE ". $condition ." GROUP BY stockID"; I have added a space just before "Group By". Hope this will help.

Pagination. Why only one page is showing?

I have been trying to get pagination to work and I have to a certain extent but it only shows one page of results.
I have 18 listings in my database and have it set to show 6 per page.
Can anyone see what the problem is?
<?php include('includes/configsql.php');
//include header template
include('layout/header.php');
//include navbar template
include('layout/navbar.php');
?>
<?php
$con = mysqli_connect($db_hostname,$db_username,$db_password,$db_database);
$sql = "SELECT COUNT(id) FROM basic WHERE status='active'";
$query = mysqli_query($con, $sql);
$row = mysqli_fetch_row($query);
$rows = $row[0];
$rows = mysqli_num_rows($query);
$page_rows = 6;
$last = ceil($rows/$page_rows);
if($last < 1){
$last = 1;
}
$pagenum = 1;
if(isset($_GET['pn'])){
$pagenum = preg_replace('#[^0-9]#', '', $_GET['pn']);
}
if ($pagenum < 1) {
$pagenum = 1;
} else if ($pagenum > $last) {
$pagenum = $last;
}
$limit = 'LIMIT ' .($pagenum - 1) * $page_rows .',' .$page_rows;
$sql = "SELECT id, name, address, telephone, email, category FROM basic WHERE status='active' ORDER BY name ASC $limit";
$query = mysqli_query($con, $sql);
$textline1 = "Basic Listing (<b>$rows</b>)";
$textline2 = "Page <b>$pagenum</b> of <b>$last</b>";
$paginationCtrls = '';
if($last != 1){
if ($pagenum > 1) {
$previous = $pagenum - 1;
$paginationCtrls .= 'Previous ';
for($i = $pagenum-4; $i < $pagenum; $i++){
if($i > 0){
$paginationCtrls .= ''.$i.' ';
}
}
}
$paginationCtrls .= ''.$pagenum.' ';
for($i = $pagenum+1; $i <= $last; $i++){
$paginationCtrls .= ''.$i.' ';
if($i >= $pagenum+4){
break;
}
}
if ($pagenum != $last) {
$next = $pagenum + 1;
$paginationCtrls .= ' Next ';
}
}
$list = '';
while($row = mysqli_fetch_array($query)){
$id = $row["id"];
$name = $row["name"];
$category = $row["category"];
$list .= '<p>'.$name.' | '.$category.' - Click the link to view this business</p>';
}
mysqli_close($con);
?>
<div id="wrapper">
<div id="bizlist">
<div id="pagination">
<h2><?php echo $textline1; ?></h2>
<p><?php echo $textline2; ?></p>
<p><?php echo $list; ?></p>
<div id="pagination_controls"><?php echo $paginationCtrls; ?></div>
</div>
</div>
<?php
//include footer template
include('layout/footer.php');
?>
I think you have to remove the line:
$rows = mysqli_num_rows($query);
It is in beginning of the script.
Another way is if you modify the first line like this:
$sql = "SELECT * FROM basic WHERE status='active'";
And remove the next 3 rows
$query = mysqli_query($con, $sql);
$row = mysqli_fetch_row($query);
$rows = $row[0];
You have to choice one of above, but not both :)

PHP MySQL Paging

I tried so many different solutions. Im new to php since 1 week, used ASP 12 years ago so I hope I can get some help.
Everything down here works fine. But there are around 1000 rows in the db and I need to split them up in pages.
<?php
$con = mysqli_connect("localhost","test","test","test")or die('could not connect to database');
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
echo "<table border='0'>
<tr>
<th>Img:</th>
<th>Text:</th>
</tr>";
$result = mysqli_query($con,"SELECT Jokes.ID, Categories.CategoryName, Jokes.CategoryID, Jokes.JokeText FROM Jokes LEFT JOIN Categories ON Jokes.CategoryID = Categories.ID ORDER BY Jokes.JokeText");
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td align='center'><img src='webimg/" . $row['CategoryName'] . ".png' height='35' width='35'></td>";
echo "<td align='left' width='80%'>" . $row['JokeText'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
Kind Regards.
You can use MySQL LIMIT for that.
I've used to do it like this:
Get the total number of rows you're paging and have a parameter like in the URL, i.e. "/p/5" or ?page=5 (I will use this for reference, easier to write code and for you to understand) for page no. 5, also do a failsafe, like this:
Say you have 10 records per page:
$page = isset($_GET['page']) ? (int) $_GET['page'] : 1;
$records_per_page = 10;
And, in your SQL you will have something like this
$start = ($page-1) * $records_per_page;
$result = mysql_query("select * from table limit {$start}, {$records_per_page}");
Kind of crude, but you should get the point and be on the right path.
For building your pagination links... that's totally up to you. You should get the total amount of rows with a "select count (PRIMARY_KEY) from table" query prior, so you can calculate the max number of pages.
What you're searching for is the LIMIT of mysql.
The usage is very simple.
For example:
"SELECT * FROM tablename LIMIT 3"
This will give you the first three results.
In your case, you need an offset, depends on the current page:
"SELECT * FROM tablename LIMIT offset,results"
The offset can be calculated, depends on how many results you want each page.
"SELECT * FROM tablename LIMIT 20,10"
This will display 10 results, start at result 20. This could be for the 3. site if you want 10 results each site.
<?php
$per_page = 10; //no. of results to display in one page
$pages_query = mysql_query("SELECT COUNT('id') FROM JOKES");//Or whatever field. this is just to check the number of results.
$pages = ceil(mysql_result($pages_query, 0) / $per_page);//to get the total no. of pages that will be there. For example if u have 60 results than no. og pages will be 60/10=6
$page = (isset($_GET['page'])) ? (int)$_GET['page'] : 1;// if the page variable in your url is set that means that u have clicked a page number. So it will be taking that page number and displaying those results
$start = ($page - 1) * $per_page;//to get the starting result of that page. If you are in say 6th page, then the starting element would be 6-1*10=50. This makes sure that the results in the previous pages are not displayed
$query = mysql_query("SELECT * FROM JOKES LIMIT $start, $per_page");//set the limit of results that page
while($query_row = mysql_fetch_assoc($query)){
echo " ur table names ";
}
$prev = $page - 1;//to set the prev page variable
$next = $page + 1;//to set the next page variable
if(!($page<=1)){
echo "<a href='Yourpagename.php?page=$prev'>Prev</a> ";
}//does not displays the prev variable if you are already one first page
if($pages>=1 && $page<=$pages){
for($x=1;$x<=$pages;$x++){
echo ($x == $page) ? '<strong>'.$x.'</strong> ' : ''.$x.' ';
}//display all the pages. Display the current page as bold
}
if(!($page>=$pages)){
echo "<a href='Your page name.php?page=$next'>Next</a>";
}//do not display next vvariable if your are in the last page
?>
Thx for all the answers. I came over this tutorial and it worked: http://www.developphp.com/view.php?tid=1349
<?php
include_once("mysqli_connection.php");
$sql = "SELECT COUNT(id) FROM testimonials WHERE approved='1'";
$query = mysqli_query($db_conx, $sql);
$row = mysqli_fetch_row($query);
$rows = $row[0];
$page_rows = 10;
$last = ceil($rows/$page_rows);
if($last < 1){
$last = 1;
}
$pagenum = 1;
if(isset($_GET['pn'])){
$pagenum = preg_replace('#[^0-9]#', '', $_GET['pn']);
}
if ($pagenum < 1) {
$pagenum = 1;
} else if ($pagenum > $last) {
$pagenum = $last;
}
$limit = 'LIMIT ' .($pagenum - 1) * $page_rows .',' .$page_rows;
$sql = "SELECT id, firstname, lastname, datemade FROM testimonials WHERE approved='1' ORDER BY id DESC $limit";
$query = mysqli_query($db_conx, $sql);
$textline1 = "Testimonials (<b>$rows</b>)";
$textline2 = "Page <b>$pagenum</b> of <b>$last</b>";
$paginationCtrls = '';
if($last != 1){
if ($pagenum > 1) {
$previous = $pagenum - 1;
$paginationCtrls .= 'Previous ';
for($i = $pagenum-4; $i < $pagenum; $i++){
if($i > 0){
$paginationCtrls .= ''.$i.' ';
}
}
}
$paginationCtrls .= ''.$pagenum.' ';
for($i = $pagenum+1; $i <= $last; $i++){
$paginationCtrls .= ''.$i.' ';
if($i >= $pagenum+4){
break;
}
}
if ($pagenum != $last) {
$next = $pagenum + 1;
$paginationCtrls .= ' Next ';
}
}
$list = '';
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
$id = $row["id"];
$firstname = $row["firstname"];
$lastname = $row["lastname"];
$datemade = $row["datemade"];
$datemade = strftime("%b %d, %Y", strtotime($datemade));
$list .= '<p>'.$firstname.' '.$lastname.' Testimonial - Click the link to view this testimonial<br>Written '.$datemade.'</p>';
}
mysqli_close($db_conx);
?>
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
body{ font-family:"Trebuchet MS", Arial, Helvetica, sans-serif;}
div#pagination_controls{font-size:21px;}
div#pagination_controls > a{ color:#06F; }
div#pagination_controls > a:visited{ color:#06F; }
</style>
</head>
<body>
<div>
<h2><?php echo $textline1; ?> Paged</h2>
<p><?php echo $textline2; ?></p>
<p><?php echo $list; ?></p>
<div id="pagination_controls"><?php echo $paginationCtrls; ?></div>
</div>
</body>
</html>

Lossing session data

I want to perform some data filtering from database. After filtering, session variable is lost and I'm getting this error:
Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in ..\test.php on line 34.
Can someone help?
FORM:
<form action= "test.php" method='get'>
<select name="Type">
<option value="winter" name="winter">winter</option>
</select>
<input type='submit' value = 'filter'>
</form>
CODE:
<?php
session_start();
$_SESSION['winter'] = $_GET['Type'];
$type = $_SESSION['winter'] ;
include "mysqlConnect.php";
//check for a page number. If not, set it to page 1
if (!(isset($_GET['pagenum']))){
$pagenum = 1;
}else{
$pagenum = $_GET['pagenum'];
}
//query for record count to setup pagination
$data = mysql_query("SELECT * FROM tblPhotos WHERE Type='$type' ");
$rows = mysql_num_rows($data);
//number of photos per page
$page_rows = 16;
//get the last page number
$last = ceil($rows/$page_rows);
//make sure the page number isn't below one, or more than last page num
if ($pagenum < 1){
$pagenum = 1;
}elseif ($pagenum > $last){
$pagenum = $last;
}
//Set the range to display in query
$max = 'limit ' .($pagenum - 1) * $page_rows .',' .$page_rows;
//get all of the photos
$dynamicList = "";
$sql = mysql_query("SELECT * FROM tblPhotos WHERE Type='$type' $max ");
//check for photos
$photoCount = mysql_num_rows($sql); //LINE 34
echo $photoCount;
if ($photoCount > 0){
while($row = mysql_fetch_array($sql)){
$photoID = $row["PhotoID"];
$photoName = $row["photoName"];
$category = $row["category"];
$dynamicList .= '
<div class="thumb">
<img class="clip" src="galleryPhotos/' . $photoID . '.jpg" alt="' . $photoName . '" width="175" border="0" />
</div>
';
}
}else{
$dynamicList = "There are no photos at this time!";
}
mysql_close();
echo '<p style="text-align:center; font-weight:bold;">Page ' . $pagenum . ' of ' . $last . '</p>';
if ($pagenum == 1){
echo '<div class="pagination" align="center"><ul>';
}else{
echo '<div class="pagination" align="center"><ul><li>« first</li>';
$previous = $pagenum-1;
}
//check if number of pages is higher than 1
if($last != 1){
//Loop from 1 to last page to create page number links
for($i = 1; $i <= $last; $i++){
echo '<li>' . $i . '</li>';
}
}
if ($pagenum == $last){
echo '</div>';
}else{
$next = $pagenum+1;
echo '<li>last »</li></ul></div>';
}
echo $dynamicList;
?>
Your Code: mysql_query("SELECT * FROM tblPhotos WHERE Type='$type' $max ");
Read the error message, it is telling you something is wrong with the query. Having looked at the query. I am inclined to agree.

Categories