PHP pagination not changing when next button is pressed - php

I am trying to do a simple pagination where it'll retrieve data from MySQL and show a previous and next button, no numbers for counting pages, although once the next button is pressed no information are updated, I am not sure if I should use a while or foreach loop.
query
pageClass.php
public function classname
{
$start_page = 0;
$per_page = 8;
if(!isset($_GET['page']))
{
$page = 1;
} else {
$page = $_GET['page'];
}
if($page<=1)
$start_page = 0;
else
$start_page = $page * $per_page - $per_page;
$this->db->setAttribute(PDO::ATTR_EMULATE_PREPARES, FALSE);
$sth = $this->db->prepare("SELECT * FROM articles ORDER BY article_uid DESC LIMIT ?, ?");
$sth->execute(array($start_page, $per_page));
$row = $sth->fetchAll();
return $row;
}
then in a .php file I am displaying it this way, I get the titles but once the buttons are pressed, no other page is opened.
index.php
foreach($latestArticles as $article)
{
$title = $latest['title'];
echo '<div>'.$title.'</div>';
}
$prev = $page - 1;
$next = $page + 1;
echo "
<a href='?page=$prev'>prev</a>
<a href='?page=$next'>next</a>
";
I don't want to put div's in the php classes as it would be a pain to find each class in folders to edit. What am I doing wrong?

First i would recommend you to change your pageClass.php to something more abstract
<?PHP
class pageClass
{
private $db;
private $articlesPerPage = 8;
private $startPage = 0;
public function __construct($db)
{
#TODO check if $db is valid PDO
$this->db = $db;
}
public function setArticlesPerPage($articlesPerPage)
{
$this->articlesPerPage = $articlesPerPage;
}
public function setStartPage($startPage)
{
$this->startPage = $startPage;
}
public function getArticles()
{
$this->db->setAttribute(PDO::ATTR_EMULATE_PREPARES, FALSE);
$query = $this->db->prepare("SELECT * FROM articles ORDER BY article_uid DESC LIMIT ?, ?");
$queryResult = $query->execute(array($this->startPage, $this->articlesPerPage));
return $queryResult;
}
}
Try to change your index.php to the following
<?PHP
$page = (int)$_GET['page'];
$pageClass = new pageClass($pdo);
if($page > 0)
{
$pageClass->setStartPage($page);
}
$lastestArticles = $pageClass->getArticles();
foreach($lastestArticles as $article)
{
echo '<div>'.$article['title'].'</div>';
}
echo 'prev';
echo 'next';
?>
NOTE: THIS IS EXAMPLE CODE. YOU SHOULD EDIT IT BEFORE COMMITING TO PRODUCTION

Related

Select and display Single Value from SQL using PHP

consider we have a database with lots of people's details.
I want to filter that result buy available data.
if the table structure is like following,
How to display only results from user with country "India".
It will be possible by accessing object attributes, but I want to add this feature to the following script.
I am not an expert and this script seems to be so difficult for me to understand.
Pagination.php
<?php
namespace Phppot;
use Phppot\DataSource;
class Pagination
{
private $ds;
function __construct()
{
require_once __DIR__ . './../lib/DataSource.php';
$this->ds = new DataSource();
}
public function getPage()
{
// adding limits to select query
require_once __DIR__ . './../Common/Config.php';
$limit = Config::LIMIT_PER_PAGE;
// Look for a GET variable page if not found default is 1.
if (isset($_GET["page"])) {
$pn = $_GET["page"];
} else {
$pn = 1;
}
$startFrom = ($pn - 1) * $limit;
$query = 'SELECT * FROM tbl_animal LIMIT ? , ?';
$paramType = 'ii';
$paramValue = array(
$startFrom,
$limit
);
$result = $this->ds->select($query, $paramType, $paramValue);
return $result;
}
public function getAllRecords()
{
$query = 'SELECT * FROM tbl_animal';
$totalRecords = $this->ds->getRecordCount($query);
return $totalRecords;
}
}
?>
I just want to filter the result.
Full script link https://phppot.com/php/how-to-add-pagination-in-php-with-mysql/
If possible, please add an option to filter the result by an animal name (Common Name), for example "Lion".
Update, here is the working code
<?php
namespace Phppot;
use Phppot\DataSource;
class Pagination
{
private $ds;
function __construct()
{
require_once __DIR__ . './../lib/DataSource.php';
$this->ds = new DataSource();
}
public function getPage()
{
// adding limits to select query
require_once __DIR__ . './../Common/Config.php';
$limit = Config::LIMIT_PER_PAGE;
// Look for a GET variable page if not found default is 1.
if (isset($_GET["page"])) {
$pn = $_GET["page"];
} else {
$pn = 1;
}
$startFrom = ($pn - 1) * $limit;
$query = 'SELECT * FROM tbl_animal WHERE common_name=Lion LIMIT ? , ?';
$paramType = 'ii';
$paramValue = array(
$startFrom,
$limit
);
$result = $this->ds->select($query, $paramType, $paramValue);
return $result;
}
public function getAllRecords()
{
$query = 'SELECT * FROM tbl_animal WHERE common_name=Lion';
$totalRecords = $this->ds->getRecordCount($query);
return $totalRecords;
}
}
?>
Found solution
<?php
namespace Phppot;
use Phppot\DataSource;
class Pagination
{
private $ds;
function __construct()
{
require_once __DIR__ . './../lib/DataSource.php';
$this->ds = new DataSource();
}
public function getPage()
{
// adding limits to select query
require_once __DIR__ . './../Common/Config.php';
$limit = Config::LIMIT_PER_PAGE;
// Look for a GET variable page if not found default is 1.
if (isset($_GET["page"])) {
$pn = $_GET["page"];
} else {
$pn = 1;
}
$startFrom = ($pn - 1) * $limit;
$query = 'SELECT * FROM tbl_animal WHERE common_name=Lion LIMIT ? , ?';
$paramType = 'ii';
$paramValue = array(
$startFrom,
$limit
);
$result = $this->ds->select($query, $paramType, $paramValue);
return $result;
}
public function getAllRecords()
{
$query = 'SELECT * FROM tbl_animal WHERE common_name=Lion';
$totalRecords = $this->ds->getRecordCount($query);
return $totalRecords;
}
}
?>

PHP dynamic previous/next links

I have a table called "product".
I'm displaying all the data from PHP product view page by using the id parameter.
With my code:
if(isset($_GET['id'])) {
$id = $_GET['id'];
}
$query = "SELECT * FROM product WHERE id = $id ";
$select_product = $db->query($query);
while($row = $db->fetch_object($select_product)) {
$status = $row->status;
if($status == 'published') {
$title = $row->title;
echo $title;
}
}
I can pull all the data I need. In this example I can echo the title.
But how do I display a dynamic next page link? That goes same for previous link.
When I try with this code:
$query = "SELECT id FROM product";
$select_ids = $db->query($query);
while($row = $db->fetch_object($select_ids)) {
$ids = $row->id;
echo $ids;
}
I can see all the pages from that table. In my case they are 20,21,22...28
Next, I've tried like this:
$query = "SELECT id from product";
$select_ids = $db->query($query);
if($select_ids->num_rows > 0) {
$next = $id + 1;
echo 'Next';
} else {
}
With this code, my "next" link successfully goes to the next page. But, when it finishes with the result, in this case when I'm on page 28, the next dynamic link goes to empty page (29). Also this is not a good approach, because if some page, let's say 25 is deleted, the next link won't skip that page.
How can I improve that dynamic "next" link?
So first of all, you need two queries one for getting the data to display and another for counting the number of rows, also we'll need some additional variables.
Here comes the code:
$page = 1;
if(isset($_GET['page'])) {
$page = $_GET['page'];
}
$numberOfResultsPerPage = 10;
$offset = $numberOfResultsPerPage * ($page - 1)
$count = $db->query("SELECT COUNT(id) as num FROM product");
while($row = $db->fetch_object($count)) {
$numberOfRows = $row->num;
}
$query = "SELECT id FROM product LIMIT ". $offset.", ".$numberOfResultsPerPage;
$select_ids = $db->query($query);
while($row = $db->fetch_object($select_ids)) {
$ids = $row->id;
echo $ids;
}
if($page > 1) {
echo 'Prev';
}
if($page < ceil($numberOfRows / $numberOfResultsPerPage)) {
echo 'Next';
}
UPDATE:
In case you need to just find the next and previous product of the product this is the solution. It is not good if you'll have lots of products but in case the number of products is under 1000 there should not be any problems:
if(isset($_GET['id'])) {
$id = $_GET['id'];
}
$query = "SELECT id from product";
$select_ids = $db->query($query);
$ids = array();
$i = 0;
while($row = $db->fetch_object($select_ids)) {
$ids[$i] = $row->id;
if($row->id == $id) {
$index = $i;
}
$i++;
}
if(isset($ids[$index-1])) {
echo 'Prev';
}
if(isset($ids[$index+1])) {
echo 'Next';
}

PHP Codeigniter Pagination

Hello i am stuck on codeigniter pagination.I am getting total rows 6, per page showing 2 row.
I am getting pagination link {Page: 1,2,3} where 1 is not clickable. On Clicking Page no:2 my link look like localhost/demo/index.php/home/press/?per_page=0/2 but i am getting error on sql
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '/2,2' at line 1
SELECT * FROM media where media_type = 'PRESS' AND id <> 0 ORDER BY id DESC LIMIT 0/2
Same Error,pagintaion link getting when i click on link : 3
I dont know how to fix this issue.I am sharing my code which i used on my controller,model and view.
My controller code:
function press()
{
$this->load->model('Home_model');
$page= $this->input->get('per_page') ? $this->input->get('per_page') : 0;
$this->load->library('Pagination');
$data['page'] = $this->input->get('page');
if($data['page'] == '') {
$data['page'] = $config['per_page'] = '2'; // Per Page
} else {
$data['page'] = $config['per_page'] = $this->input->get('page');
}
$config['first_url']='0';
$pageno = $this->input->get('per_page');
if($pageno == ''){
$pageno = '0';
}
$url_to_paging = $this->config->item('base_url');
$config['base_url'] = $url_to_paging.'home/press/?per_page='.$page;
$return = $this->Home_model->pressdata($config['per_page'],$pageno, $data);
$data['pressdata'] = $return['result']; // Get Two Row Data
$config['total_rows'] = $return['count']; // Total Count 6
$this->pagination->initialize($config);
$this->load->view('press',$data);
}
Model :
function pressdata($pg_num, $offset, $content)
{
if($offset == ''){
$offset = '0';
}
$sql = "SELECT * FROM media where media_type = 'PRESS' AND id <> 0";
if($pg_num!=0 || $pg_num!="")
{
$sql .= " ORDER BY id DESC LIMIT ".$offset.",".$pg_num;
}
$query = $this->db->query($sql);
$sql_couint = "SELECT * FROM media where media_type = 'PRESS' AND id <> 0";
$query1 = $this->db->query($sql_couint);
$ret['result'] = $query->result();
$ret['count'] = $query1->num_rows();
return $ret;
}
Try it like this
$this->load->library('pagination');
$this->load->model('Home_model');
$config['base_url'] = base_url().'home/press/;
$config['total_rows'] = 200; // Total no of rows returned from the database table
$config['uri_segment'] = 3; // It is the page no,used as offset in model
$offset = 0;
if ($this->uri->segment($config['uri_segment']) != "") {
$offset = $this->uri->segment($config['uri_segment']);
}
$config['per_page'] = 20; // you can change it as you want
$return = $this->Home_model->pressdata($config['per_page'],$offset, $data);
$this->pagination->initialize($config);
In your model you can do something like this
function pressdata($per_page, $offset) {
if($per_page !== '' && $offset !== '') {
$this->db->limit($per_page, $offset);
}
//rest of your query
}
Don't copy paste it though, I just wanted to give you an idea. Modify it, implement it according to your needs. Let me know if it worked. Go through CodeIgniter's pagination library for more detailed documentation.
Finally i found the way to solve this problem.
Here are the final code for Controller, Model, View.
Controller Code :
function press()
{
$this->load->library('pagination');
$url_to_paging = $this->config->item('base_url'); // URL here (www.example.com)
$config['base_url'] = $url_to_paging.'home/press/'; // www.example.com/home/press
$config['per_page'] = '4'; // Per Page Data Show 4
$data = array();
$return = $this->Home_model->pressdata($config['per_page'],$this->uri->segment(3));
$data['pressdata'] = $return['result'];
$config['total_rows'] = $return['count'];
$this->pagination->initialize($config);
$this->load->view('press', $data);
}
Model Code :
function pressdata($num, $offset)
{
if($offset == '')
{
$offset = '0';
}
$sql = "SELECT * FROM media where media_type = 'PRESS' AND id <> 0 ";
if($num!='' || $offset!='')
{
$sql .= " order by id desc limit ".$offset.",".$num."";
}
$query = $this->db->query($sql);
$sql_count = "SELECT * FROM media WHERE media_type = 'PRESS' AND id <> 0";
$query1 = $this->db->query($sql_count);
$ret['result'] = $query->result_array();
$ret['count'] = $query1->num_rows();
return $ret;
}
View Page for pagination link :
if($this->pagination->create_links()) { ?>
<div style="clear:both; border-top: solid 1px #e9ecf1;"></div>
<div style="float:right;">
<span class="pagination" style="margin:0px; border:none;">
<?php echo $this->pagination->create_links(); ?>
</span>
</div>
<?php }
function pressdata($pg_num, $offset, $content)
{
if($offset == ''){
$offset = '0';
}
$sql = "SELECT * FROM media where media_type = 'PRESS' AND id => 0";
if($pg_num!=0 || $pg_num!="")
{
$sql .= " ORDER BY id DESC LIMIT ".$offset.",".$pg_num;
}
$query = $this->db->query($sql);
$sql_couint = "SELECT * FROM media where media_type = 'PRESS' AND id => 0";
$query1 = $this->db->query($sql_couint);
$ret['result'] = $query->result();
$ret['count'] = $query1->num_rows();
return $ret;
}
<-------id should be greater and equal to zero----->

No database selected in php?

i am working and new to php i am getting no database selected error;
here is the my code which is dd.php
<?php
include('database.php'); //include of db config file
$pdo = Database::connect();
$per_page = 2; // number of results to show per page
$sql = 'SELECT * FROM customers ORDER BY id DESC';
$result=mysql_query($sql) or die("ERROR".mysql_error()."*****".$sql);
$total_results = mysql_num_rows($sql);
$total_pages = ceil($total_results / $per_page);//total pages we going to have
//-------------if page is setcheck------------------//
if (isset($_GET['page'])) {
$show_page = $_GET['page']; //it will telles the current page
if ($show_page > 0 && $show_page <= $total_pages) {
$start = ($show_page - 1) * $per_page;
$end = $start + $per_page;
} else {
// error - show first set of results
$start = 0;
$end = $per_page;
}
} else {
// if page isn't set, show first set of results
$start = 0;
$end = $per_page;
}
// display pagination
$page = intval($_GET['page']);
$tpages=$total_pages;
if ($page <= 0)
$page = 1;
?>
fix error in this code one after another i am getting new error like mysql_num_rows() error ODBC#localhost acess denied????
plz help me out??
here is my database.php
<?php
class Database
{
private static $dbName = 'crud_tutorial' ;
private static $dbHost = 'localhost' ;
private static $dbUsername = 'root';
private static $dbUserPassword = '';
private static $cont = null;
public function __construct() {
die('Init function is not allowed');
}
public static function connect()
{
// One connection through whole application
if ( null == self::$cont )
{
try
{
{
self::$cont = new PDO( "mysql:host=".self::$dbHost.";"."dbname=".self::$dbName, self::$dbUsername, self::$dbUserPassword);
}
catch(PDOException $e){
die($e->getMessage());
}
}
return self::$cont;
}
public static function disconnect()
{
self::$cont = null;
}
}
?>
problem is due to mysql_* is deprecated replacing with mysqli_ works

Passing Multiple Variables Through Pages PHP MYSQL

The following code is working fine for the first page. It is a query based on user input from a form. I have 2 issues. The first one is when i click next page i get undefined index and undefined variable error which means the variables are not passed. The second question is how can i make a query and paginate it based on the user filled/selected values in the form? Some users may not fill all the values.
Here is my code: NB: The form method is GET. I have tried REQUEST and POST too. All the same error. Thanks in advance guys.
<?php
if (isset($_POST['Submit']))
$name = mysql_real_escape_string($_GET['name']);
$email = mysql_real_escape_string($_GET['email']);
$age = mysql_real_escape_string($_GET['age']);
$height = mysql_real_escape_string($_GET['height']);
include_once "conn.php"; //connect to db and table
$rs = mysql_query("SELECT COUNT(*) FROM people WHERE name='$name' AND email='$email' AND age='$age' AND height='$height'");
$rw = mysql_fetch_array($rs);
$numrows = $rw[0];
if ($numrows== 0) die("No Results Found");
$rowsperpage = 7;
$totalpages = ceil($numrows / $rowsperpage);
if (isset($_GET['currentpage']) && is_numeric($_GET['currentpage'])) {
$currentpage = (int) $_GET['currentpage'];
} else {
$currentpage = 1;
}
if ($currentpage > $totalpages) {
$currentpage = $totalpages;
}
if ($currentpage < 1) {
$currentpage = 1;
}
$offset = ($currentpage - 1) * $rowsperpage;
$query = mysql_query("SELECT * FROM people WHERE name='$name' AND email='$email' AND age='$age' AND height='$height' ORDER BY time DESC LIMIT $offset, $rowsperpage");
//print my tables here
while($row = mysql_fetch_array($query))
{
$uniqueid = $row['age'];
//output stuff here
}
//close sql
$range = 3;
if ($currentpage > 1) {
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=1&name=$name&email=$email&age=$age&height=$height'> Go To Page 1</a> ";
$prevpage = $currentpage - 1;
echo "<a href='{$_SERVER['PHP_SELF']}?currentpage=$prevpage&name=$name&email=$email&age=$age&height=$height'> Previous Page</a>";
}
for ($x = ($currentpage - $range); $x < (($currentpage + $range) + 1); $x++) {
if (($x > 0) && ($x <= $totalpages)) {
if ($x == $currentpage) {
echo " <font size=4 color=red>[<b>$x</b>] </font>";
} else {
echo "<a href='{$_SERVER['PHP_SELF']}?currentpage=$x&name=$name&email=$email&age=$age&height=$height'>$x</a>";
}
}
}
if ($currentpage != $totalpages) {
$nextpage = $currentpage + 1;
echo "<a href='{$_SERVER['PHP_SELF']}?currentpage=$nextpage&name=$name&email=$email&age=$age&height=$height'>Next Page</font></a>";
echo "<a href='{$_SERVER['PHP_SELF']}?currentpage=$totalpages&name=$name&email=$email&age=$age&height=$height'>Last Page</a> ";
}
?>
The form submits as GET. Because this one, the POST variable isn't set. And you're not defining the first variable (missing brackets?). Furthermore, Submit is the only submitted value with a capital. Is this intentional?
if (isset($_GET['Submit'])) {
$name = mysql_real_escape_string($_GET['name']);
$email = mysql_real_escape_string($_GET['email']);
$age = mysql_real_escape_string($_GET['age']);
$height = mysql_real_escape_string($_GET['height']);
}
More ideally, because you want to ommit values, you'll probably want to check each variable individually for existence. And if it's not set (or empty), don't add that field in your WHERE clause.
$name = isset($_GET['name']) ? mysql_real_escape_string($_GET['name']) : null;
// ... process the other fields in same way ...
or spanned over multiple lines: EDIT: just noticed I was missing a closing ) in the two blocks below.
$name = null;
if (isset($_GET['name'])) {
$name = mysql_real_escape_string($_GET['name']);
}
// ... process the other fields in same way ...
or even:
$name = null;
if (isset($_GET['name']))
$name = mysql_real_escape_string($_GET['name']);
// ... process the other fields in same way ...
Dynamic query
Then, make your query a bit more dynamic. Like, adding all your available WHERE parameters to an array. It makes things easier.
// Store conditions in array
$whereConditions = array();
if (!empty($name)) {
$whereConditions['name'] = $name;
}
if (!empty($email)) {
$whereConditions['email'] = $email;
}
if ($age && $age > 0) {
$whereConditions['age'] = $age;
}
if ($height && $height > 0) {
$whereConditions['height'] = $height;
}
// Start building your query dynamically
$query = 'SELECT * FROM people';
// Making things easier here. Just flatten your array down.
$conditions = array();
foreach ($whereConditions as $field => $value) {
$conditions[] = sprintf("%s = '%s'", $field, $value);
}
// Join all conditions with AND
$where = implode(' AND ', $conditions);
// Add where clause, if there are conditions
if (!empty($where)) {
$query .= ' WHERE ' . $where;
}
$query .= " ORDER BY time DESC LIMIT {$offset}, {$rowsperpage}";
Final notes
Keep in mind to use prepared queries if you're allowing user input. And the mysql_ extension is deprecated. Switch to mysqli_ or PDO.

Categories