Sqlite pagination with PDO - php

I have managed to paginate by sqlite database using PDO, but being new to databases I am wondering if there is a better or efficient way of doing this? Here is the code:
<?php
try
{
$db = new PDO('sqlite:comments.s3db');
$per_page = '3';
$result = $db->query("SELECT id FROM com ");
$rows = $result ->fetchAll();
$total_records = count($rows);
$pages = ceil($total_records / $per_page);
$page = (isset ($_GET['page'])) ? (int) $_GET['page'] : 1 ;
$start = ($page - 1) * $per_page;
$query = $db->query("SELECT * FROM com LIMIT $start , $per_page");
while($row = $query->fetch(PDO::FETCH_ASSOC)){
echo '<br>' . $row['id'] . '<br>' . $row['name'] . '<br>' . $row['email'] . '<br>';
} ?>
<br><br>
<?php
if ($pages >= 1 && $page <= $pages){
//if ($page>1 && $page <= $pages){$previous=($page -1); echo 'Previous';}
for($x=1; $x<=$pages; $x++){ echo ($x == $page) ? ' <strong>'.$x.'</strong> ' : ' '.$x.' ';}
//if ($page>1 && $page <= $pages){ $next=($page+1) ; echo 'Next';}
}
####################### Close Database #######################
$db = NULL;
}
catch(PDOException $e)
{
print 'Exception : '.$e->getMessage();
}
?>

At first don't select all records with 'id' in first query. Make it easily with selecting COUNT(id). In result u'll get total rows count:
SELECT COUNT(id FROM) com
Second notice - format your code. Make it more readable.

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.

Add pagination to my search engine

How can I add pagination to a search engine results page?
I have build a search engine but there are hundreds of thousands of results for every search so I want to add pages to it.
The results of the search engine are outputted in a table.
I have started to learn php and sql recently...
How can I add those pages?
I have tried this so far but with no success:
<?php
$con = mysqli_connect(xxxx);
mysqli_select_db($con, 'Data') or die("could not find the database!");
$output = '';
$results_per_page = 1000;
//positioning
if(isset($_GET['search']))
{
$starttime = microtime(true); //TIME
$searchkey = $_GET['search'];
$query = mysqli_query($con, "SELECT * FROM table1 WHERE email LIKE '%$searchkey%'") or die("Could not search") ;
$count = mysqli_num_rows($query);
// count number of pages for the search
$number_of_pages = ceil($count/$results_per_page);
// determine which page number visitor is currently on
if (!isset($_GET['page']))
{
$page = 1;
}
else
{
$page = $_GET['page'];
}
// LIMIT
$this_page_first_result = ($page-1)*$results_per_page;
if ($count == 0)
{
echo "</br>";
$output = 'There are no search results !' ;
}
else
{
echo '<table class="myTable">';
echo "<tr><th>aaa</th><th>bbb</th></tr>";
$query = mysqli_query($con, "SELECT * FROM table1 WHERE email LIKE '%$searchkey%' LIMIT " . $this_page_first_result . ',' . $results_per_page" ") or die("Could not search") ;
while ($row = mysqli_fetch_array($query))
{
$email = preg_replace('/(' . $searchkey . ')/i', '<mark>\1</mark>', $row["aaa"]);
$password = $row['bbb'];
echo "<tr><td>";
echo $aaa;
echo "</td><td>";
echo $bbb;
echo "</td></tr>";
$output = '</table>';
}
//echo "</table>";
$endtime = microtime(true);
$duration = $endtime - $starttime;
echo "</br>";
if ($count == 1)
{
echo "<div class=resinfo>";
echo '<div>'."1 result was found for '$searchkey' in $duration seconds.".'</div>'.'</br>';
echo "</div>";
}
else
{
echo "<div class=resinfo>";
echo '<div>'."$count results were found for '$searchkey' in $duration seconds.".'</div>'.'</br>';
echo "</div>";
}
}
echo $output;
}
//LINKS to other pages
for ($page = 1; $page<=$number_of_pages;$page++){
echo '' . $page . '';
}
?>
What have I done wrong, what can I improve to make it work?
Thanks a lot for your help!
It is not a good idea to build a pagination from scratch, instead use a lib like this: https://github.com/KnpLabs/knp-components/blob/master/doc/pager/intro.md

converting my old script to PDO results do not show?

ok si im not very fimiliar with PDO im just starting off, could someone help me here why my results will not display? the pages are working but no data would show ..
<?php
require_once 'db/_db.php';
$stmt = $db->prepare("SELECT * FROM article");
$stmt->execute();
$result = $stmt->fetchAll();
$total_rows = $stmt->rowCount();
//$allRecords = mysql_query('select * from article');
//$total_rows = mysql_num_rows($allRecords);
//$base_url = 'https://localhost/pagi/'; //
global $per_page;
$num_links = 4;
$total_rows = $total_rows;
$cur_page = 1;
if(isset($_GET['page']))
{
$cur_page = $_GET['page'];
$cur_page = ($cur_page < 1)? 1 : $cur_page; //if page no. in url is less then 1 or -ve
}
$offset = ($cur_page-1)*$per_page; //setting offset
$pages = ceil($total_rows/$per_page);
$start = (($cur_page - $num_links) > 0) ? ($cur_page - ($num_links - 1)) : 1;
$end = (($cur_page + $num_links) < $pages) ? ($cur_page + $num_links) : $pages;
//$res = mysql_query("SELECT * FROM article ORDER BY id DESC LIMIT ".$per_page." OFFSET ".$offset);
$stm = $db->prepare("SELECT * FROM article ORDER BY id DESC LIMIT ".$per_page." OFFSET ".$offset);
$stm->execute();
$res = $stm->fetchAll();
$rows = $stm->rowCount();
if($rows < 1){
header("Location: news-events.php");
exit;
}
if(is_resource($result))
{
foreach( $res as $row ) {
$desc = $row["ne_article"];
$img = $row['ne_image'];
if(!empty($img)){
$img = '<br/><img src="uploads/images/'.$img.'" alt="" class="responsive-shrink">';
}else{
$img = '';
}
$youtube = $row["ne_youtube"];
if(!empty($youtube)){
$youtube = '<br/><div class="video-container"><iframe src="http://www.youtube.com/embed/'.$youtube.'"></iframe></div>';
}else{
$youtube = '';
}
//shortenString($row['ne_article']);
?>
<h4><?php echo $row['ne_title']; ?></h4>
<h5><b>Views:</b> <?php echo $row['views']; ?>, <b>Posted on:</b> <?php echo format_date($row['created']); ?></h5>
<?php echo $img; ?>
<?php echo $youtube; ?>
<p>
<br/><?php echo bbcode(nl2br(shortenString($desc))); ?>
</p>
<div id="pagelink">
Read more...</button>
</div>
<?php
}
}
?>
<div id="pagination">
<div id="pagiCount">
<br/><br/>
<?php
if(isset($pages))
{
if($pages > 1)
{ if($cur_page > $num_links) // for taking to page 1 //
{ $dir = "First";
echo '<span id="prev"> '.$dir.' </span>';
}
if($cur_page > 1)
{
$dir = "Prev";
echo '<span id="prev"> '.$dir.' </span>';
}
for($x=$start ; $x<=$end ;$x++)
{
echo ($x == $cur_page) ? '<strong>'.$x.'</strong> ':''.$x.' ';
}
if($cur_page < $pages )
{ $dir = "Next";
echo '<span id="next"> '.$dir.' </span>';
}
if($cur_page < ($pages-$num_links) )
{ $dir = "Last";
echo ''.$dir.' ';
}
}
}
?>
would really appreciate your time and help
You are doing nearly everything wrong. And you did with old mysql as well
To get the number of records in database you should never select all the rows, nor fetch them. You have to select the count already.
$total_rows = $pdo->query("SELECT count(1) FROM article")->fetchColumn();
is how it have to be done with PDO.
Besides, for the other query you should use prepared statements.
Finally, you have to take out all the useless verifications and start with foreach right away:
$stm = $db->prepare("SELECT * FROM article ORDER BY id DESC LIMIT ?,?");
$stm->execute([$offset,$per_page]);
$res = $stm->fetchAll();
foreach( $res as $row ) {
And read up on setting the error mode properly here.
check if you have problem with the quotes... when you echo html code inside ' ' if you have " " and again inside '' like this example echo ' " '' " ' you will have problem. you should use \' in order to avoid these problem here echo ' '.$dir.' ';

Pagination Database Query Woes

I have been working at this all day and still at 8pm have had no luck. I was wondering if you guys can give me some advice on fixing it. I am building an Upload - gif sharing system for University.
Here is my code anyway -
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
mysql_connect("localhost","root","root") or die("Top Query");
mysql_select_db("UPLOAD") or die(mysql_error());
$count_query = mysql_query("SELECT NULL FROM details");
$count = mysql_num_rows($count_query);
//pagination
if(isset($_GET['page'])){
$page = preg_replace("#[^0-9]#","",$_GET['page']);
}else{
$page= 1;
}
$perPage = 5;
$lastPage = ceil($count / $perPage);
if($page < 1){
$page = 1;
}else if($page > $lastPage){
$page = $lastPage;
}
$limit = "LIMIT " .($page -1) * $perPage . ", $perPage";
//Query and gifs
$query = mysql_query("SELECT * FROM details ORDER BY date_added DESC") or die("2nd Query");
//Puts it into an array
$pagination="";
if($lastPage != 1){
if($page != $lastPage){
$next = $page + 1;
$pagination.='More';
}
if($page != 1){
$prev = $page - 1;
$pagination.='Back';
}
}
?>
And then the output in the html -
<?php
while($info = mysql_fetch_array($query)){
$shortlink = "".$info['photo']." " ;
//Outputs the image and other data
echo "<article class='upload-post'>" . "<div class='crop'>";
echo "<a href=uploads/".$info['photo'].">";
echo "<img class='scale-with-grid' src=uploads/".$info['photo'] .">"."</a>";
echo "</div>";
echo "".$info['name'] . "<br/>";
echo "Reaction ".$info['reaction'] ."<br/>";
echo "In " .$info['category'] ." <br/>";
echo "On " .$info['date_added'] ." <br/>";
echo "Link: $shortlink";
echo "</article>";
}
?>
<?php echo $pagination;?>
I can toggle between pages but its not limiting the number of posts displayed on the page. Id really appreciate the help as the deadline isn't too far away.
Thanks a bunch in advance!
You never append $limit to your query.
Try the follwing as a replacement...
...
//Query and gifs
$query = mysql_query("SELECT * FROM details ORDER BY date_added DESC ".$limit) or die("2nd Query");
//Puts it into an array
...

Pagination not displaying PHP PDO

Im trying to paginate my query only nothing is being outputted, can anybody see where im going wrong? Im very new to PHP/PDO
else {
try
{
$per_page = '3';
$result = $conn->prepare("SELECT * FROM directory WHERE user_active != ''");
$rows = $result ->fetchAll();
$total_records = count($rows);
$pages = ceil($total_records / $per_page);
$page = (isset ($_GET['page'])) ? (int) $_GET['page'] : 1 ;
$start = ($page - 1) * $per_page;
$query = $conn->prepare("SELECT * FROM directory WHERE user_active != ''");
while($row = $query->fetch(PDO::FETCH_ASSOC)){
echo '<br>' . $row['id'] . '<br>' . $row['First_Name'] . '<br>' . $row['Surname'] . '<br>';
} ?>
<br><br>
<?php
if ($pages >= 1 && $page <= $pages){
//if ($page>1 && $page <= $pages){$previous=($page -1); echo 'Previous';}
for($x=1; $x<=$pages; $x++){ echo ($x == $page) ? ' <strong>'.$x.'</strong> ' : ' '.$x.' ';}
//if ($page>1 && $page <= $pages){ $next=($page+1) ; echo 'Next';}
}
####################### Close Database #######################
$db = NULL;
}
catch(PDOException $e)
{
print 'Exception : '.$e->getMessage();
}
};
You never execute the query.
$result->execute();
$rows = $result ->fetchAll();
$query->execute();
while($row = $query->fetch(PDO::FETCH_ASSOC)){
Also it's better to use LIMIT in your query. Something like that:
//to get need page
$per_page = 3;
$page = (isset ($_GET['page'])) ? (int) $_GET['page'] : 1 ;
$result = $conn->prepare(
"SELECT * FROM directory
WHERE user_active != ''
LIMIT ".(($page - 1) * $per_page).", ".$per_page
);
$result->execute();
$rows = $result ->fetchAll();
//to get count of pages
$result = $conn->prepare(
"SELECT COUNT(*) FROM directory
WHERE user_active != ''"
);
$result->execute();
$total-pages = reset($result->fetch(PDO::FETCH_NUM));

Categories