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));
Related
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.
I am trying to fetch data from mysql and display them category wise with pagination. I am getting the category wise result but when i change my page data of every category changed too i need to change the data of only category selected . i have setup multi category news option for user so they can add one news to multiple category .help me out here is my code what am trying.
<?php
include'../config.php';
// number of rows to show per page
$rowsperpage = 2;
$main = array();
$cat = array();
$qry = "SELECT * FROM app_category order by id DESC ";
$res = mysqli_query($con, $qry);
$records = mysqli_fetch_array($res, MYSQLI_ASSOC);
$rowcount = mysqli_num_rows($res);
if ($rowcount > 1) {
foreach ($res as $records) {
$cat = $records;
// lets find out how many rows are in the MySQL table
$sql = "SELECT COUNT(*) FROM app_news WHERE cat_id='" . $cat['id'] . "'";
$result = mysqli_query($con, $sql) or die(mysql_error());
$r = mysqli_fetch_row($result);
$numrows = $r[0];
// find out total pages
$totalpages = ceil($numrows / $rowsperpage);
if (isset($_GET['currentpage']) && is_numeric($_GET['currentpage'])) {
$currentpage = (int) $_GET['currentpage'];
} else {
$currentpage = 1; // default page number
}
// if current page is greater than total pages
if ($currentpage > $totalpages) {
// set current page to last page
$currentpage = $totalpages;
}
// if current page is less than first page
if ($currentpage < 1) {
// set current page to first page
$currentpage = 1;
}
// the offset of the list, based on current page
$offset = ($currentpage - 1) * $rowsperpage;
$qry = "SELECT * FROM app_news where cat_id='" . $cat['id'] . "' LIMIT $offset, $rowsperpage";
$res1 = mysqli_query($con, $qry);
$json1 = array();
while ($records1 = mysqli_fetch_array($res1, MYSQLI_ASSOC)) {
$news_id = $records1['news_id'];
$news_title = $records1['title'];
$news_des = $records1['description'];
$news_des = htmlspecialchars_decode(str_replace(""", "\"", $news_des));
$news_image = $records1['image'];
$json1[] = array("news_id" => $news_id, "title" => $news_title, "image" => $imgapi . $news_image, "description" => $news_des);
}
$cat['All-news'] = array("total no of pages" => $totalpages, "data" => $json1);
$main[] = $cat;
unset($json1);
unset($json);
unset($cat);
}
unset($totalpages);
//header("Content-Type: application/json; charset=utf-8");
echo json_encode($main, JSON_UNESCAPED_SLASHES);
unset($main);
mysqli_close($con);
} else {
$minfo = array("success" => 'false', "message" => 'No result to display. Please add First category.');
$jsondata = json_encode($minfo);
print_r($jsondata);
mysqli_close($conn);
exit();
}
I have Split my code in two request get and post
get is for first time initialisation and then i use post method for getting scroll amount from app:
here is code :
<?php
include'../config.php';
$main = array();
$cat = array();
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
$rowsperpage = 5;
$qry = "SELECT * FROM app_category order by id DESC ";
$res = mysqli_query($con, $qry);
$records = mysqli_fetch_array($res, MYSQLI_ASSOC);
$rowcount = mysqli_num_rows($res);
if ($rowcount > 1) {
foreach ($res as $records) {
$cat = $records;
// lets find out how many rows are in the MySQL table
$sql = "SELECT COUNT(*) FROM app_news WHERE cat_id='" . $cat['id'] . "'";
$result = mysqli_query($con, $sql) or die(mysql_error());
$r = mysqli_fetch_row($result);
$numrows = $r[0];
// find out total pages
$totalpages = ceil($numrows / $rowsperpage);
if (isset($_GET['currentpage']) && is_numeric($_GET['currentpage'])) {
$currentpage = (int) $_GET['currentpage'];
} else {
$currentpage = 1; // default page number
}
// if current page is greater than total pages
if ($currentpage > $totalpages) {
// set current page to last page
$currentpage = $totalpages;
}
// if current page is less than first page
if ($currentpage < 1) {
// set current page to first page
$currentpage = 1;
}
// the offset of the list, based on current page
$offset = ($currentpage - 1) * $rowsperpage;
$qry = "SELECT * FROM app_news where cat_id='" . $cat['id'] . "' LIMIT $offset, $rowsperpage";
$res1 = mysqli_query($con, $qry);
$json1 = array();
while ($records1 = mysqli_fetch_array($res1, MYSQLI_ASSOC)) {
$news_id = $records1['news_id'];
$news_title = $records1['title'];
$news_des = $records1['description'];
$news_des = htmlspecialchars_decode(str_replace(""", "\"", $news_des));
$news_image = $records1['image'];
$json1[] = array("news_id" => $news_id, "title" => $news_title, "image" => $imgapi . $news_image, "description" => $news_des);
}
$cat['All-news'] = array("total no of pages" => $totalpages, "data" => $json1);
$main[] = $cat;
unset($json1);
unset($json);
unset($cat);
}
unset($totalpages);
//header("Content-Type: application/json; charset=utf-8");
echo json_encode($main, JSON_UNESCAPED_SLASHES);
unset($main);
mysqli_close($con);
} else {
$minfo = array("success" => 'false', "message" => 'No result to display. Please add First category.');
$jsondata = json_encode($minfo);
print_r($jsondata);
mysqli_close($conn);
exit();
}
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
include_once'../config.php';
if (isset($_POST['cat_id'])) {
$rowsperpage = 5;
$catid = $_POST['cat_id'];
$qry = "SELECT * FROM app_category WHERE id='" . $catid . "' ";
$res = mysqli_query($con, $qry);
while ($row = mysqli_fetch_array($res, MYSQLI_ASSOC)) {
$cat=$row;
}
// lets find out how many rows are in the MySQL table
$sql = "SELECT COUNT(*) FROM app_news WHERE cat_id='" . $cat['id'] . "'";
$result = mysqli_query($con, $sql) or die(mysql_error());
$r = mysqli_fetch_row($result);
$numrows = $r[0];
// find out total pages
$totalpages = ceil($numrows / $rowsperpage);
///Checkeing for page requested
if (isset($_POST['currentpage']) && is_numeric($_POST['currentpage'])) {
$currentpage = (int) $_POST['currentpage'];
} else {
$currentpage = 1; // default page number
}
// if current page is greater than total pages
if ($currentpage > $totalpages) {
// set current page to last page
$currentpage = $totalpages;
}
// if current page is less than first page
if ($currentpage < 1) {
// set current page to first page
$currentpage = 1;
}
// the offset of the list, based on current page
$offset = ($currentpage - 1) * $rowsperpage;
$qry = "SELECT * FROM app_news where cat_id='" . $catid . "' LIMIT $offset, $rowsperpage";
$res1 = mysqli_query($con, $qry);
$json1 = array();
while ($records1 = mysqli_fetch_array($res1, MYSQLI_ASSOC)) {
$news_id = $records1['news_id'];
$news_title = $records1['title'];
$news_des = $records1['description'];
$news_des = htmlspecialchars_decode(str_replace(""", "\"", $news_des));
$news_image = $records1['image'];
$json1[] = array("news_id" => $news_id, "title" => $news_title, "image" => $imgapi . $news_image, "description" => $news_des);
}
$cat['All-news'] = array("total no of pages" => $totalpages, "data" => $json1);
$main[] = $cat;
unset($json1);
unset($json);
unset($cat);
echo json_encode($main, JSON_UNESCAPED_SLASHES);
unset($main);
unset($totalpages);
mysqli_close($con);
}
}
I have a php pagination page with post submit by user to search something, query mysql in first page is ok, but in NEXT page, i have get white blank page.
Below is the paging code.
$_SESSION['nationality'] = $_POST['nationality'];
$reclimit = 2;
if(isset($_GET['page'])){
$page = $_GET['page'];
} else {
$page = 1;
}
$start = (($page-1) * $reclimit);
$sql = "SELECT userid, name, LEFT(hkid, 4) as hkid, description, nationality, photo_1, photo_2, photo_3 FROM $tbl_name WHERE `nationality` LIKE '%$_SESSION[nationality]%'";
$records = $con->query($sql);
$total = $records->num_rows;
$tpages = ceil($total / $reclimit);
$rec = "SELECT userid, name, LEFT(hkid, 4) as hkid, description, nationality, photo_1, photo_2, photo_3 FROM $tbl_name WHERE `nationality` LIKE '%$_SESSION[nationality]%' LIMIT $start, $reclimit";
$records = $con->query($rec);
while ($row = mysqli_fetch_assoc($records)){
// Loop record
}
// Paging
echo '<ul class="pagination pagination-lg">';
for( $i=1; $i <= $tpages; $i++ ) {
$active = $i == $page ? 'class="active"' : '';
echo "<li $active ><a href='$_SERVER[PHP_SELF]?page=" .$i. "'>" .$i. "</a></li>";
}
echo '</ul>';
This works for me:
<?php
$limit =3;
if (!isset($_GET['pg'])) {
$pg = 1;
} else {
$pg = $_GET['pg'];
}
$start = ($pg - 1 ) * $limit;
$sql = "SELECT * FROM tableName LIMIT $start , $limit";
?>
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.' ';
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.