converting my old script to PDO results do not show? - php

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.' ';

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.

keep post variable in php pagination

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";
?>

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));

Sqlite pagination with PDO

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.

Pagination links not working

I've searched through the web and can't really find what's the problem with my code. The next and prev links are not working. it only gets the first entry.
Hope you guys can help with this! Thanks.
<?php
// ROWS DISPLAYED PER PAGE
$rows_per_page = 1;
// GET PAGE NUMBER
$page = $_GET['page'];
$offset = (!empty($page)) ? $page : $page = 1;
// URL CLEAN UP
$self = $_SERVER['PHP_SELF']."?".$_SERVER['QUERY_STRING'];
$self = str_replace("page={$offset}", "", $self);
// GET LIST OF STATES
$offset = ($page) ? ($page - 1) * $rows_per_page : 0;
$id = $_GET['id'];
$sql = "SELECT * FROM updates WHERE update_categoryID = '$id' ORDER BY update_date DESC LIMIT {$offset},{$rows_per_page}";
$result = mysql_query($sql)or die('Error, query failed');
// GET NUMBER OF PAGES
$query1 = "SELECT * FROM updates WHERE update_categoryID = '$id'";
$result1 = mysql_query($query1)or die('Error, query failed');
$total = mysql_num_rows($result1);
$NumPgs = ceil($total/$rows_per_page);
while($row = mysql_fetch_assoc($result))
{
?>
<h2><?php echo $row['update_title']; ?></h2>
<p class="datetime"><?php echo $row['update_date'];?></p>
<br>
<p class="post"><?php echo $row['update_content'];?></p>
Post a Comment
<?php
}
?>
<span style="float:right">
<? if ($NumPgs > 0 && $page!=1) {
echo "<<Prev "; } ?>
[Page <?php echo $page; ?>]
<? if ($page < $NumPgs) {
echo " Next>>"; } ?>
<b><? echo $offset+1;?> to <? echo $offset+$rows_per_page;?>, of <? echo $total; ?> Entries</b>
</span>
</div>
Uhm maybe your page param is appended to the query string, try this :
$self = $_SERVER['PHP_SELF']."?".
preg_replace( $_SERVER[ 'QUERY_STRING' ], 'page=[0-9]+', '');
instead of :
// URL CLEAN UP
$self = $_SERVER['PHP_SELF']."?".$_SERVER['QUERY_STRING'];
$self = str_replace("page={$offset}", "", $self);
Short open tags are not working in your case.
http://us3.php.net/echo
http://us3.php.net/manual/en/ini.core.php#ini.short-open-tag
Try the following code.
<?php
// ROWS DISPLAYED PER PAGE
$rows_per_page = 1;
// GET PAGE NUMBER
$page = $_GET['page'];
$offset = (!empty($page)) ? $page : $page = 1;
// URL CLEAN UP
$self = $_SERVER['PHP_SELF']."?".$_SERVER['QUERY_STRING'];
$self = str_replace("page={$offset}", "", $self);
// GET LIST OF STATES
$offset = ($page) ? ($page - 1) * $rows_per_page : 0;
$id = $_GET['id'];
$sql = "SELECT * FROM updates WHERE update_categoryID = '$id' ORDER BY update_date DESC LIMIT {$offset},{$rows_per_page}";
$result = mysql_query($sql)or die('Error, query failed');
// GET NUMBER OF PAGES
$query1 = "SELECT * FROM updates WHERE update_categoryID = '$id'";
$result1 = mysql_query($query1)or die('Error, query failed');
$total = mysql_num_rows($result1);
$NumPgs = ceil($total/$rows_per_page);
while($row = mysql_fetch_assoc($result))
{
?>
<h2><?php echo $row['update_title']; ?></h2>
<p class="datetime"><?php echo $row['update_date'];?></p>
<br>
<p class="post"><?php echo $row['update_content'];?></p>
Post a Comment
<?php
}
?>
<span style="float:right">
<? echo ($prev = ($NumPgs > 0 && $page!=1) ? "Prev ":
"Prev "); ?>
[Page <?php echo $page; ?>]
<? echo ($next = ($page < $NumPgs) ? "Next":
"Next");?>
<b> <? echo $offset+1?> to <?=$offset+$rows_per_page?>, of <? echo $total?> Entries</b>
</span>
</div>

Categories