I found this awesome code online to help with pagination, and it's working well, the only problem is: each page displays the same 4 rows.
Any ideas will be much appreciated
<?php
//Include the PS_Pagination class
include('includes/ps_pagination.php');
//Connect to mysql db
$conn = mysql_connect("localhost", "root", "root");
mysql_select_db('database',$conn);
$sql = "SELECT * FROM studies WHERE niche = '{$_GET['niche']}'";
//Create a PS_Pagination object
$pager = new PS_Pagination($conn,$sql,4,5);
//The paginate() function returns a mysql
//result set for the current page
$rs = $pager->paginate();
//Loop through the result set
while($row = mysql_fetch_assoc($rs)) {
$a=0;
while ($a < $num) {
$id=mysql_result($result,$a,"id");
$title=mysql_result($result,$a,"title");
$strategies=mysql_result($result,$a,"strategies");
$client=mysql_result($result,$a,"client");
$copy=mysql_result($result,$a,"copy");
$thumbmedia=mysql_result($result,$a,"thumbmedia");
$niche=mysql_result($result,$a,"niche");
echo '<div class="container"><p class="subheadred">'.$title.'</p></div>';
echo '<div class="containerstudy"><div class="column1"><p class="subheadsmall">Strategies</p><p class="sidebarred">'.$strategies.'</p>';
echo '<p class="subheadsmall">Client</p><p class="sidebargrey">'.$client.'</p></div>';
echo '<div class="column2"><p class="bodygrey">'.substr($copy, 0, 300).'...more</p></div>';
echo '<div class="column3"><img src="images/'.$thumbmedia.'" height="160" /></div></div>';
$a++;
}
}
//Display the navigation
echo $pager->renderNav();
?>
This is the included file:
<?php
/**
* PHPSense Pagination Class
*
* PHP tutorials and scripts
*
* #package PHPSense
* #author Jatinder Singh Thind
* #copyright Copyright (c) 2006, Jatinder Singh Thind
* #link http://www.phpsense.com
*/
// ------------------------------------------------------------------------
class PS_Pagination {
var $php_self;
var $rows_per_page; //Number of records to display per page
var $total_rows; //Total number of rows returned by the query
var $links_per_page; //Number of links to display per page
var $sql;
var $debug = false;
var $conn;
var $page;
var $max_pages;
var $offset;
/**
* Constructor
*
* #param resource $connection Mysql connection link
* #param string $sql SQL query to paginate. Example : SELECT * FROM users
* #param integer $rows_per_page Number of records to display per page. Defaults to 10
* #param integer $links_per_page Number of links to display per page. Defaults to 5
*/
function PS_Pagination($connection, $sql, $rows_per_page = 1, $links_per_page = 5) {
$this->conn = $connection;
$this->sql = $sql;
$this->rows_per_page = $rows_per_page;
$this->links_per_page = $links_per_page;
$this->php_self = htmlspecialchars($_SERVER['PHP_SELF']);
if(isset($_GET['page'])) {
$this->page = intval($_GET['page']);
}
}
/**
* Executes the SQL query and initializes internal variables
*
* #access public
* #return resource
*/
function paginate() {
if(!$this->conn) {
if($this->debug) echo "MySQL connection missing<br />";
return false;
}
$all_rs = #mysql_query($this->sql);
if(!$all_rs) {
if($this->debug) echo "SQL query failed. Check your query.<br />";
return false;
}
$this->total_rows = mysql_num_rows($all_rs);
#mysql_close($all_rs);
$this->max_pages = ceil($this->total_rows/$this->rows_per_page);
//Check the page value just in case someone is trying to input an aribitrary value
if($this->page > $this->max_pages || $this->page <= 0) {
$this->page = 1;
}
//Calculate Offset
$this->offset = $this->rows_per_page * ($this->page-1);
//Fetch the required result set
$rs = #mysql_query($this->sql." LIMIT {$this->offset}, {$this->rows_per_page}");
if(!$rs) {
if($this->debug) echo "Pagination query failed. Check your query.<br />";
return false;
}
return $rs;
}
/**
* Display the link to the first page
*
* #access public
* #param string $tag Text string to be displayed as the link. Defaults to 'First'
* #return string
*/
function renderFirst($tag='First') {
if($this->page == 1) {
return $tag;
}
else {
return ''.$tag.'';
}
}
/**
* Display the link to the last page
*
* #access public
* #param string $tag Text string to be displayed as the link. Defaults to 'Last'
* #return string
*/
function renderLast($tag='Last') {
if($this->page == $this->max_pages) {
return $tag;
}
else {
return ''.$tag.'';
}
}
/**
* Display the next link
*
* #access public
* #param string $tag Text string to be displayed as the link. Defaults to '>>'
* #return string
*/
function renderNext($tag=' >>') {
if($this->page < $this->max_pages) {
return ''.$tag.'';
}
else {
return $tag;
}
}
/**
* Display the previous link
*
* #access public
* #param string $tag Text string to be displayed as the link. Defaults to '<<'
* #return string
*/
function renderPrev($tag='<<') {
if($this->page > 1) {
return ''.$tag.'';
}
else {
return $tag;
}
}
/**
* Display the page links
*
* #access public
* #return string
*/
function renderNav() {
for($i=1;$i<=$this->max_pages;$i+=$this->links_per_page) {
if($this->page >= $i) {
$start = $i;
}
}
if($this->max_pages > $this->links_per_page) {
$end = $start+$this->links_per_page;
if($end > $this->max_pages) $end = $this->max_pages+1;
}
else {
$end = $this->max_pages;
}
$links = '';
$niche = $_GET['niche'];
for( $i=$start ; $i<$end ; $i++) {
if($i == $this->page) {
$links .= " $i ";
}
else {
$links .= ' '.$i.' ';
}
}
return $links;
}
/**
* Display full pagination navigation
*
* #access public
* #return string
*/
function renderFullNav() {
return $this->renderFirst().' '.$this->renderPrev().' '.$this->renderNav().' '.$this->renderNext().' '.$this->renderLast();
}
/**
* Set debug mode
*
* #access public
* #param bool $debug Set to TRUE to enable debug messages
* #return void
*/
function setDebug($debug) {
$this->debug = $debug;
}
}
?>
Just at first glance i see your query is repeating itself from the beginning every time you run it, so that means every time you run it it searches from the beggining. you need a counter to tell it where to start from on the next page. something like:
$sql = "SELECT * FROM studies WHERE niche = '{$_GET['niche']}' limit $startPoint, $offset";
that way the offset is the same as the number of items you want per page and the $startPoint is the point at which the search beggins at the next iteration.
somehting like this would work:
if(!$startPoint){$startPoint = 0;}else{$startPoint = {$_GET['$startPoint'];}
within your code pass the start point back to the query and increasing it by the offset after each iteration.
Please bear in mind i've not taking into consideration stuff like injection, and the fact that the variable $num doesn't seem to come from anywhere in the 1st file. I cant see where you initialized it so as to test $a against it.
After looking at your code more in depth i found a few things that need to be changed to get it work in the least here is the changed code:
<?php
//Include the PS_Pagination class
include('includes/ps_pagination.php');
//Connect to mysql db
$conn = mysql_connect("localhost", "root", "root");
mysql_select_db('database',$conn);
$sql = "SELECT * FROM studies";// WHERE niche = '{$_GET['niche']}'";
//Create a PS_Pagination object
$pager = new PS_Pagination($conn,$sql,4,5);
//The paginate() function returns a mysql
//result set for the current page
$rs = $pager->paginate();
//Loop through the result set
while($row = mysql_fetch_assoc($rs)) {
// $a=0;
// while ($a < $num) {
// $id=mysql_result($result,$a,"id");
// $title=mysql_result($result,$a,"title");
// $strategies=mysql_result($result,$a,"strategies");
// $client=mysql_result($result,$a,"client");
// $copy=mysql_result($result,$a,"copy");
// $thumbmedia=mysql_result($result,$a,"thumbmedia");
// $niche=mysql_result($result,$a,"niche");
$id=$row['id'];
$title=$row['title'];
$strategies=$row['strategies'];
$client=$row['client'];
$copy=$row['copy'];
$thumbmedia=$row['thumbmedia'];
$niche=$row['niche'];
echo '<div class="container"><p class="subheadred">'.$title.'</p></div>';
echo '<div class="containerstudy"><div class="column1"><p class="subheadsmall">Strategies</p><p class="sidebarred">'.$strategies.'</p>';
echo '<p class="subheadsmall">Client</p><p class="sidebargrey">'.$client.'</p></div>';
echo '<div class="column2"><p class="bodygrey">'.substr($copy, 0, 300).'...more</p></div>';
echo '<div class="column3"><img src="images/'.$thumbmedia.'" height="160" /></div></div>';
// $a++;
// }
}
//Display the navigation
echo $pager->renderNav();
?>
Notice i have commented out some part that where not necessary
the variable $a was meaningless as it compared to $num which doesn't exist therefore nothing would show. Now these lines:
// $id=mysql_result($result,$a,"id");
// $title=mysql_result($result,$a,"title");
// $strategies=mysql_result($result,$a,"strategies");
// $client=mysql_result($result,$a,"client");
// $copy=mysql_result($result,$a,"copy");
// $thumbmedia=mysql_result($result,$a,"thumbmedia");
// $niche=mysql_result($result,$a,"niche");
where also wrong as you are trying to get the result set from $result. at no place had you put the result set into $result the class you have imported does that and puts the result set into an identifier called $rs.
Since you are using $row = mysql_fetch_assoc($rs) to read through the result set then to get the variables all you need to do is get the column row through an array like this
$id=$row['id'];
and so on. once you do that then the code should work as expected. However this brings us back to this:
$sql = "SELECT * FROM studies WHERE niche = '{$_GET['niche']}'";
i had to get the last part out in that this variable is not getting passed back into the query string (seeing you are using get), the other problem is the 1st time you load the page this variable 'niche' doesn't exist so the 1st time you run the code you will get a blank page, unless this script is accessed through a link that passes in this variable. at this point i have left it commented out as am not sure what you were trying to do through niche.
Hope that helps.
Do you have page set in your query string?
I think that if you changed the paginate function, so that it would have one parameter $page and you would set $this->page = $page at the begining of the function, it would work.
You would also have to change the calling of this function in your code to $pager->paginate($_GET['page']).
The pager is also very inefficient, it gets the whole query just to find out, how many rows does the response have. I would use something like:
$all_rs = #mysql_query('SELECT COUNT(*) FROM (' . $this->sql . ')');
if(!$all_rs) {
if($this->debug) echo "SQL query failed. Check your query.<br />";
return false;
}
$this->total_rows = mysql_result($all_rs, 0, 0);
#mysql_close($all_rs);
I'm not sure what this pagination library does with the index of the rows, but you are always setting $a to 0. Perhaps the index is not relative to the page but to the overall recordset being returned?
In other words, what if you set $a to 0 on page 1, 4 on page 2, etc.
You should be able to use $rows_per_page and $page to calculate it. Or perhaps that is the $offset value, so that you set $a to offset and loop it until you hit $rows_per_page additional rows.
Edit clarifying solution:
So what I see you could do is:
$a=0;
while ($a < $pager->rows_per_page) {
$row = $a + $pager->offset;
$id=mysql_result($result,$row,"id");
$title=mysql_result($result,$row,"title");
$strategies=mysql_result($result,$row,"strategies");
$client=mysql_result($result,$row,"client");
$copy=mysql_result($result,$row,"copy");
$thumbmedia=mysql_result($result,$row,"thumbmedia");
$niche=mysql_result($result,$row,"niche");
...
$a++;
}
Related
I have a PHP function I got from the web that uses bcmath functions:
function SteamID64to32($steamId64) {
$iServer = "1";
if(bcmod($steamId64, "2") == "0") {
$iServer = "0";
}
$steamId64 = bcsub($steamId64,$iServer);
if(bccomp("76561197960265728",$steamId64) == -1) {
$steamId64 = bcsub($steamId64,"76561197960265728");
}
$steamId64 = bcdiv($steamId64, "2");
return ("STEAM_0:" . $iServer . ":" . $steamId64);
}
For any valid input the function will at random times add ".0000000000" to the output.
Ex:
$input = 76561198014791430;
SteamID64to32($input);
//result for each run
STEAM_0:0:27262851
STEAM_0:0:27262851.0000000000
STEAM_0:0:27262851
STEAM_0:0:27262851
STEAM_0:0:27262851.0000000000
STEAM_0:0:27262851
STEAM_0:0:27262851.0000000000
STEAM_0:0:27262851.0000000000
STEAM_0:0:27262851.0000000000
This was tested on 2 different nginx servers running php-fpm.
Please help me understand what is wrong here. Thanks
The answer provided by JD doesn't account for all possible STEAM_ ID types, namely, anything that is in the STEAM_0:1 range. This block of code will:
<?php
function Steam64ToSteam32($Steam64ID)
{
$offset = $Steam64ID - 76561197960265728;
$id = ($offset / 2);
if($offset % 2 != 0)
{
$Steam32ID = 'STEAM_0:1:' . bcsub($id, '0.5');
}
else
{
$Steam32ID = "STEAM_0:0:" . $id;
}
return $Steam32ID;
}
echo Steam64ToSteam32(76561197960435530);
echo "<br/>";
echo Steam64ToSteam32(76561197990323733);
echo "<br/>";
echo Steam64ToSteam32(76561198014791430);
?>
This outputs
STEAM_0:0:84901
STEAM_0:1:15029002
STEAM_0:0:27262851
The first one is for a Valve employee and someone who's had a Steam account since 2003 (hence the low ID), the second is a random profile I found on VACBanned which had an ID in the STEAM_0:1 range. The third is the ID you provided in your sample code.
I found this: SteamProfile
/**
* This file is part of SteamProfile.
*
* Written by Nico Bergemann <barracuda415#yahoo.de>
* Copyright 2009 Nico Bergemann
*
* SteamProfile is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SteamProfile is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SteamProfile. If not, see <http://www.gnu.org/licenses/>.
*/
// thanks to voogru for the id transformation algorithm (http://forums.alliedmods.net/showthread.php?t=60899)
class SteamID {
private $sSteamID = '';
private $sSteamComID = '';
const STEAMID64_BASE = '76561197960265728';
public function __construct($sID) {
// make sure the bcmath extension is loaded
if(!extension_loaded('bcmath')) {
throw new RuntimeException("BCMath extension required");
}
if($this->isValidSteamID($sID)) {
$this->sSteamID = $sID;
$this->sSteamComID = $this->convertToSteamComID($sID);
} elseif($this->isValidComID($sID)) {
$this->sSteamID = $this->convertToSteamID($sID);
$this->sSteamComID = $sID;
} else {
$this->sSteamID = '';
$this->sSteamComID = '';
}
}
public function getSteamID() {
return $this->sSteamID;
}
public function getSteamComID() {
return $this->sSteamComID;
}
public function isValid() {
return $this->sSteamID != '';
}
private function isValidSteamID($sSteamID) {
return preg_match('/^(STEAM_)?[0-5]:[0-9]:\d+$/i', $sSteamID);
}
private function isValidComID($sSteamComID) {
// anything else than a number is invalid
// (is_numeric() doesn't work for 64 bit integers)
if(!preg_match('/^\d+$/i', $sSteamComID)) {
return false;
}
// the community id must be bigger than STEAMID64_BASE
if(bccomp(self::STEAMID64_BASE, $sSteamComID) == 1) {
return false;
}
// TODO: Upper limit?
return true;
}
private function convertToSteamComID($sSteamID) {
$aTMP = explode(':', $sSteamID);
$sServer = $aTMP[1];
$sAuth = $aTMP[2];
if((count($aTMP) == 3) && $sAuth != '0' && is_numeric($sServer) && is_numeric($sAuth)) {
$sComID = bcmul($sAuth, "2"); // multipy Auth-ID with 2
$sComID = bcadd($sComID, $sServer); // add Server-ID
$sComID = bcadd($sComID, self::STEAMID64_BASE); // add this odd long number
// It seems that PHP appends ".0000000000" at the end sometimes.
// I can't find a reason for this, so I'll take the dirty way...
$sComID = str_replace('.0000000000', '', $sComID);
return $sComID;
} else {
throw new RuntimeException("Unable to convert Steam-ID");
}
}
private function convertToSteamID($sSteamComID) {
$sServer = bcmod($sSteamComID, '2') == '0' ? '0' : '1';
$sCommID = bcsub($sSteamComID, $sServer);
$sCommID = bcsub($sCommID, self::STEAMID64_BASE);
$sAuth = bcdiv($sCommID, '2');
return "STEAM_0:$sServer:$sAuth";
}
}
i take the code of Bayesian from site http://www.ibm.com/developerworks/library/wa-bayes3/
i am not able to remove the error of undefined from the select query.
here is the code :
<?php
/**
* #package NaiveBayes
* #author Paul Meagher <paul#datavore.com>
* #license PHP License v3.0
* #version 0.2
*
* This class must be supplied with training example data, attribute names,
* and class names. Once this information is supplied, you can then invoke
* the learn and classify methods.
*/
class NaiveBayes {
/**
* Database table to use.
*/
var $table = null;
/**
* 1D array of attributes names. Attribute names should
* correspond to field names in the specified database
* table.
*/
var $attributes = array();
/**
* 1D array of attribute values to classify.
*/
var $attribute_values = null;
/**
* Specifies table column holding classification values.
*/
var $class = array();
/**
* Specifies allowable classification values.
*/
var $class_values = array();
/**
* 3D array containing joint frequency infomation about
* how class names and attribute names covary. Used to
* derive the likelihood array in the classify method.
*/
var $joint_frequency = array();
/**
* 1D array containing prior probability of each class name.
*/
var $priors = array();
/**
* 1D array containing likeliood of the data for each class.
*/
var $likelihoods = array();
/**
* 1D array containing the posterior probability of each class
* name given the supplied attribute values.
*/
var $posterior = array();
/**
* Denotes the number of training examples used for learning.
*/
var $n = 0;
/**
* When the classifier method is called, $predict is set to
* class name with the highest posterior probability.
*/
var $predict = null;
/**
* Set database table to use.
*/
function setTable($table)
{
$this->table = $table;
}
/**
* Set attribute columns to use. The attribute columns should
* correspond to fields in your database table.
*/
function setAttributes($columns)
{
foreach($columns as $column)
{
$this->attributes[] = $column;
}
}
/**
* Set classification column names to use.
*/
function setClass($column) {
$this->class = $column;
}
/**
* Set classification names to use.
*/
function setClassValues($values) {
foreach($values as $value) {
$this->class_values[] = $value;
}
}
function inimat($lr, $ur, $lc, $uc, &$a, $x){
for(; $lr<=$ur; $lr++)
for($j=$lc; $j<=$uc; $j++) $a[$lr][$j]=$x;
}
/**
* Learn the prior probability of each class and the
* joint frequency of each class and attribute.
*/
function learn()
{
// include connection file
include("connect.php");
// parse array
foreach ($this->attributes as $attribute)
// get field list
$field_list = substr($attribute, 0, -1);
// parse array
foreach ($this->class_values as $class) {
// make an sql query
$sql = "SELECT $field_list FROM " . $this->table . " WHERE " . $this->class . "='$class'";
// execute sql query
$result = mysql_query($sql);
$this->priors["$class"] = mysql_num_rows($result);
while ($row = mysql_fetch_assoc($result))
{
foreach ($this->attributes as $attribute) {
// if row attribute haven't any data then set default value
$attribute_value = isset($row[$attribute]) ? $row[$attribute] : 0;
$this->joint_frequency[$class][$attribute][$attribute_value]++;
}
}
}
}
/**
* Given a set of attribute values, this routine will
* predict the class they most likley belong to.
*/
function classify($attribute_values) {
$this->attribute_values = $attribute_values;
$this->n = array_sum($this->priors);
$this->max = 0;
foreach($this->class_values as $class) {
$counter = 0;
$this->likelihoods[$class] = 1;
foreach($this->attributes as $attribute) {
$attribute_value = $attribute_values[$counter];
$joint_freq = $this->joint_frequency[$class][$attribute][$attribute_value];
$likelihood = $joint_freq / $this->priors[$class];
if ($joint_freq > 0) {
$this->likelihoods[$class] = $this->likelihoods[$class] * $likelihood;
}
$counter++;
}
$prior = $this->priors[$class] / $this->n;
$this->posterior[$class] = $this->likelihoods[$class] * $prior;
if ($this->posterior[$class] > $this->max) {
$this->predict = $class;
$this->max = $this->posterior[$class];
}
}
}
/**
* Output the posterior probabilities that were computed by
* the classify method.
*/
function toHTML() {
foreach($this->class_values as $class) {
$equation = "P($this->class = ". $class ." | ";
$counter = 0;
foreach($this->attributes as $attribute) {
$attribute_value = $this->attribute_values[$counter];
$equation .= $attribute ."=". $attribute_value ." & ";
$counter++;
}
$equation = substr($equation, 0, -7);
$equation .= ") = ". $this->posterior[$class];
if ($class == $this->predict) {
$equation .= " <sup>*</sup>";
}
echo $equation ."<br />";
}
}
}
?>
it give error
Notice: Undefined index: q1 in C:\wamp\www\Bayes3\NaiveBayes.php on line 130 : $attribute_value = $row[$attribute];
Notice: Undefined index: 0 in C:\wamp\www\Bayes3\NaiveBayes.php on line 131 :
$this->joint_frequency[$class][$attribute][$attribute_value]++;
Notice: Undefined index: 1 in C:\wamp\www\Bayes3\NaiveBayes.php on line 150 :
$joint_freq = $this->joint_frequency[$class][$attribute][$attribute_value];
kindly help me in this
this can be done through isset function
You can use isset function:
<?php
/**
* Learn the prior probability of each class and the
* joint frequency of each class and attribute.
*/
function learn()
{
// include connection file
include("connect.php");
// parse array
foreach ($this->attributes as $attribute)
// get field list
$field_list = substr($attribute, 0, -1);
// parse array
foreach ($this->class_values as $class) {
// make an sql query
$sql = "SELECT $field_list FROM " . $this->table . " WHERE " . $this->class . "='$class'";
// execute sql query
$result = mysql_query($sql);
$this->priors["$class"] = mysql_num_rows($result);
while ($row = mysql_fetch_assoc($result)) {
foreach ($this->attributes as $attribute) {
// if row attribute haven't any data then set default value
$attribute_value = isset($row[$attribute]) ? $row[$attribute] : 0;
$this->joint_frequency[$class][$attribute][$attribute_value]++;
}
}
}
}
?>
To suppress the error you can add '#' symbol before the variable which is throwing the error.
Add # like
$attribute_value = #$row[$attribute];
I have a tree login page as my first page in a survey. The issue is that , if the user does not select any node and clicks on the next button he is redirected to the same page . The problem is that he does not get any error message .
I want the user to get an error message 'Please select a group'
Please look into the below code which does this action
(P.S check the Display() function )
Correct me where I am going wrong
<?php
/**
* File: TreeLoginWidget.php
*
*
* Purpose: display tree page.
*
* Dependents: none
*
* Dependencies: SurveyItem
*
* Classes:
* 1. PinWidget
*
* Interface/public functions:
*
* Notes: ???
*
* Todo: none
*
**/
class DisplayTreeLoginWidget extends DisplayItem
{
function DisplayTreeLoginWidget(& $sourceObj)
{
// debug
if( $pDebugTraceFlag == _ID_FLAG_ON ) GDebugTraceFunc( __CLASS__." :: ".__FUNCTION__ );
$this->node = 0;
$surveywidget = getDataFromSession("surveywidget");
DisplayItem::DisplayItem();
$_SESSION["profile"]["rootNode"]=0;
if($_GET["nodeId"]) {
setDataToSession("postVar","");
}
$this->sourceObj =& $sourceObj;
}
/**
* Purpose: display pin page label text
*
* Input Params: none
*
* Output Params: none
*
* Return Value: none
*
* Notes:
*/
function display()
{
global $skin_path,$skin,$path;
setDataToSession("skipPage", 0);
setDataToSession('HideSave&Resume',0);
$currentPageNumber = currentPageNumber();
if($currentPageNumber!=1) {
setDataToSession('HideSave&Resume',1);
}
echo "<script type=\"text/javascript\" src=\"".$path."../lib/java/commonFuncs.js\"></script>";
// include the header
include_once ("../lib/include/path.inc.php");
include_once ("../lib/include/jshelper.php");
include_once("display/tree.inc.php");
include_once("display/commonTreeLayout.php");
include_once ("../lib/include/commonTreeCode.php");
setUpTreeAppProperty();
$postVar = getDataFromSession("postVar");
if(is_array($postVar)) {
$_POST = $postVar;
}
if($this->sourceObj->displayType == "expanded") {
$postVar["Expand_All"] = "Expand All";
$this->sourceObj->displayType = "";
}
if($this->sourceObj->levelShowing != "") {
setDataToSession("levelShowing",$this->sourceObj->levelShowing);
}
setUpElist($postVar, $_GET);
$verifiedStartingNode = getTreeStartingNode();
/** $matchedIdArr contains matched nodeIds or empty if no matches found/no search performed */
$matchedIdArr = doSearch($verifiedStartingNode, $postVar);
$eList = getEList();
$Tree = new TreeWithRadioButton($this->sourceObj);
$Tree->reSetupElist();
$startingNode = &$Tree->nodesArr[$verifiedStartingNode];
echo "<div class=\"body2 IE6trans\">";
displaySearchTable();
if(!$postVar["searchSubmit"]) {
$matchedIdArr = array(getDataFromSession("data,node_id"));
}
displayTree('Search Organization Structure', '', '', $startingNode, $eList, $matchedIdArr, $maxDepth, get_path_prefix(),$this->sourceObj->_errorMsg,$this->sourceObj->_prompt);
echo "<script type=\"text/javascript\">";
echo "$(document).ready(function () { $('input[name=\"wildText\"]').keyup(function(event){ if(event.keyCode == 13){ $('input[name=\"searchSubmit\"]').click(); } }); });";
echo "</script>";
echo "</div>";
}
/**
* Purpose: storing error message to _errorMsg
*
* Input Params: none
*
* Output Params: none
*
* Return Value: Boolean - true or false
*
* Notes:
*/
function validate()
{
// debug
if( $pDebugTraceFlag == _ID_FLAG_ON ) GDebugTraceFunc( __CLASS__." :: ".__FUNCTION__ );
$surveywidget = getDataFromSession('surveywidget');
$this->getPostData();
$this->sourceObj->_errorMsg = "";
$lastVisitedWidgetOid_Tree = getDataFromSession("lastVisitedWidgetOid_Tree");
setDataToSession("lastVisitedWidgetOid" , $lastVisitedWidgetOid_Tree);
setLoginUserLanguage($this->node);
$operations = ((strcmp($this->operation,getText2($surveywidget->saveResumeButtonText)) == 0)||
(strcmp($this->operation,getText2($surveywidget->backButtonText)) == 0)||
(strcmp($this->operation,getText2($surveywidget->nextButtonText)) == 0));
if(($operations) && ($this->node != "")) {
setDataToSession("data,node_id",$this->node);
// used to track the node id assigned to this pin when more than one login is used
setDataToSession("tree_login,node_id",$this->node);
setDataToSession("tree_login_before_saveresume,node_id",$this->node);
//Custom -
$oids = getListOfOidAndNodes(Array($this->node));
$_SESSION["conditionNodeList"] = $oids;
//End Custom
if(!getDataFromSession('multiLoginIndex')) {
$multiLoginIndex = 1;
} else {
$multiLoginIndex = getDataFromSession('multiLoginIndex');
}
$multiLoginIndex++;
setDataToSession("multiLoginIndex",$multiLoginIndex);
$this->sourceObj->_errorMsg = "";
} else if(($operations) && ($this->node == "")){
$this->sourceObj->_errorMsg = "Please select a group";
return false;
} else {
return false;
}
if($this->node == "") {
$this->node = 0;
}
// user click save&resume before visiting login page, we are redirecting to login page, That time user enter invalid node_id we are mainting save&resume flag to 1 for displaying submitbutton(it act like as save&resume)
if(getDataFromSession('save&resumeflag') == 1) {
setDataToSession('save&resumeloginpage',1);
}
return true;
}
/**
* Purpose: get post data
*
* Input Params: none
*
* Output Params: none
*
* Return Value: none
*
* Notes:
*/
function getPostData()
{
// debug
if( $pDebugTraceFlag == _ID_FLAG_ON ) GDebugTraceFunc( __CLASS__." :: ".__FUNCTION__ );
$postVar["exactText"] = (empty($_REQUEST["exactText"])==1) ?"" :stripslashes($_REQUEST["exactText"]);
$postVar["wildText"] = (empty($_REQUEST["wildText"])==1) ?"" :stripslashes($_REQUEST["wildText"]);
$postVar["searchSubmit"] = (empty($_REQUEST["searchSubmit"])==1) ?"" :$_REQUEST["searchSubmit"];
$postVar["Collapse_All"] = (empty($_REQUEST["Collapse_All"])==1) ?"" :$_REQUEST["Collapse_All"];
$postVar["idText"] = (empty($_REQUEST["idText"])==1) ?"" :$_REQUEST["idText"];
$postVar["node"] = (empty($_REQUEST["node"])==1) ?"" :$_REQUEST["node"];
$this->node = ($_REQUEST["node"] == "") ?"" :$_REQUEST["node"];
$this->operation = (empty($_REQUEST["Operation"])==1) ?"" :$_REQUEST["Operation"];
if($postVar["Collapse_All"]) {
$postVar["wildText"] = "";
}
setDataToSession('postVar',$postVar);
setDataToSession('Operation',$this->operation);
setDataToSession('node',$this->node);
}
}
?>
Your code is long, and I didn't read it.
But the typical way to do this is to pass a url parameter, and if the parameter exists print it out as a message.
So for some reason I am trying to figure out why my pagination isnt working properly. I get it to move from page 1 to 2 but it wont go to page 3 for some reason. I checked to see if the query from the DB was correct and it was so not sure where I am going wrong.
$per_page = '4';
$tenure_sql = 'SELECT COUNT(id) as count
FROM people.bywu
WHERE type <> 0
AND status = "approved"';
$tenure_query = mysql_query( $tenure_sql, DB );
$tenure_count = mysql_fetch_object( $tenure_query );
$tenure_count = $tenure_count -> count;
$tenure_pages = ceil( $tenure_count / $per_page );
<div class="pagination" id="tenure_pages">
<
Stories <span id="tenure_low" class="current_low"><?= $tenure_count ? '1':'0' ?></span>-<span id="tenure_high" class="current_high"><?= $tenure_count > 4 ? $per_page : $tenure_count ?></span> of <span class="total"><?= $tenure_count ?></span>
>
<span class="pages" style="display:none;"><?= $tenure_pages ?></span>
<?
for( $i = 1; $i < $tenure_pages + 1; $i++ )
{
echo '' . $i . ' ';
} // for
?>
Scrapped away from kohana pagination class, i think you will find it useful if you know any basics about php classes.
Usage :
$pager = Pagination::factory(array('current_page' => $_GET['page'], 'total_items' => $total_items, 'items_per_page' => 20));
if ($pager->next_page) { /* etc.......*/ }
<?php
class Pagination {
protected $config = array(
'current_page' => 1,
'total_items' => 0,
'items_per_page' => 10
);
// Current page number
protected $current_page;
// Total item count
protected $total_items;
// How many items to show per page
protected $items_per_page;
// Total page count
protected $total_pages;
// Item offset for the first item displayed on the current page
protected $current_first_item;
// Item offset for the last item displayed on the current page
protected $current_last_item;
// Previous page number; FALSE if the current page is the first one
protected $previous_page;
// Next page number; FALSE if the current page is the last one
protected $next_page;
// First page number; FALSE if the current page is the first one
protected $first_page;
// Last page number; FALSE if the current page is the last one
protected $last_page;
// Query offset
protected $offset;
/**
* Creates a new Pagination object.
*
* #param array configuration
* #return Pagination
*/
public static function factory(array $config = array())
{
return new Pagination($config);
}
/**
* Creates a new Pagination object.
*
* #param array configuration
* #return void
*/
public function __construct(array $config = array())
{
// Pagination setup
$this->setup($config);
}
/**
* Loads configuration settings into the object and (re)calculates pagination if needed.
* Allows you to update config settings after a Pagination object has been constructed.
*
* #param array configuration
* #return object Pagination
*/
public function setup(array $config = array())
{
// Only (re)calculate pagination when needed
if ($this->current_page === NULL
OR isset($config['current_page'])
OR isset($config['total_items'])
OR isset($config['items_per_page']))
{
// Calculate and clean all pagination variables
$this->current_page = (int) $this->config['current_page'];
$this->total_items = (int) max(0, $this->config['total_items']);
$this->items_per_page = (int) max(1, $this->config['items_per_page']);
$this->total_pages = (int) ceil($this->total_items / $this->items_per_page);
$this->current_page = (int) min(max(1, $this->current_page), max(1, $this->total_pages));
$this->current_first_item = (int) min((($this->current_page - 1) * $this->items_per_page) + 1, $this->total_items);
$this->current_last_item = (int) min($this->current_first_item + $this->items_per_page - 1, $this->total_items);
$this->previous_page = ($this->current_page > 1) ? $this->current_page - 1 : FALSE;
$this->next_page = ($this->current_page < $this->total_pages) ? $this->current_page + 1 : FALSE;
$this->first_page = ($this->current_page === 1) ? FALSE : 1;
$this->last_page = ($this->current_page >= $this->total_pages) ? FALSE : $this->total_pages;
$this->offset = (int) (($this->current_page - 1) * $this->items_per_page);
}
// Chainable method
return $this;
}
/**
* Returns a Pagination property.
*
* #param string property name
* #return mixed Pagination property; NULL if not found
*/
public function __get($key)
{
return isset($this->$key) ? $this->$key : NULL;
}
/**
* Updates a single config setting, and recalculates pagination if needed.
*
* #param string config key
* #param mixed config value
* #return void
*/
public function __set($key, $value)
{
$this->setup(array($key => $value));
}
} // End Pagination
?>
Unless the count() you get from the database is 9 or larger, you'd never see a 3.
ceil(0/4) -> 0
...
ceil(8/4) -> 2
ceil(9/4) -> 3
So... how many articles are there in the database that match the conditions in your query?
You don't show how you're passing around the "current page" count in your code, so how does the code know which page you're on at the moment?
$total_pages = 8;
$current_page = $_GET['curPage'];
for ($i = 1; $i <= $total_pages; $i++) {
$class = ($i == $current_page) ? ' class="current"' : '';
echo <<<EOL
<a href="page.php?curPage=$i"$class>$i</a>
EOL;
}
I am looking for a php pagination class, I have used a rather simple one in the past and it is no longer supported.
I was wondering if anyone had any recommendations ?
It seems pointless to build my own when there are probably so many good ones out there.
After more searching I decided that before I use a frameworked version I should fully understand what is involved in a paginator. So I built one myself. Thanks for the suggestions though!
I would suggest Zend_Paginator for the following reasons
It's loosely coupled and doesn't require the entire library.
The ZF community is larger than the PEAR community and is actively running security audits on code, and releasing maintenance versions.
It separates data sources by using the Adapter Pattern, and there are numerous examples of front end UI pattern implementations in the documentation.
Have you tried PEAR::Pager? Usage examples here.
you can try this:
Zebra_Pagination, a generic, Twitter Bootstrap compatible, pagination class written in PHP
check the link below:
http://stefangabos.ro/php-libraries/zebra-pagination
// pagination class
class Pagination
{
// database handle
private $dbh;
// total records in table
private $total_records;
// limit of items per page
private $limit;
// total number of pages needed
private $total_pages;
// first and back links
private $firstBack;
// next and last links
private $nextLast;
// where are we among all pages?
private $where;
public function __construct($dbh) {
$this->dbh = $dbh;
}
// determines the total number of records in table
public function totalRecords($query, array $params)
{
$stmt = $this->dbh->prepare($query);
$stmt->execute($params);
$this->total_records = $stmt->fetchAll(PDO::FETCH_COLUMN)[0];
if (!$this->total_records) {
echo 'No records found!';
return;
}
}
// sets limit and number of pages
public function setLimit($limit)
{
$this->limit = $limit;
// determines how many pages there will be
if (!empty($this->total_records)) {
$this->total_pages = ceil($this->total_records / $this->limit);
}
}
// determine what the current page is also, it returns the current page
public function page()
{
$pageno = (int)(isset($_GET['pageno'])) ? $_GET['pageno'] : $pageno = 1;
// out of range check
if ($pageno > $this->total_pages) {
$pageno = $this->total_pages;
} elseif ($pageno < 1) {
$pageno = 1;
}
// links
if ($pageno > 1) {
// backtrack
$prevpage = $pageno -1;
// 'first' and 'back' links
$this->firstBack = "<div class='first-back'><a href='$_SERVER[PHP_SELF]?pageno=1'>First</a> <a href='$_SERVER[PHP_SELF]?pageno=$prevpage'>Back</a></div>";
}
$this->where = "<div class='page-count'>(Page $pageno of $this->total_pages)</div>";
if ($pageno < $this->total_pages) {
// forward
$nextpage = $pageno + 1;
// 'next' and 'last' links
$this->nextLast = "<div class='next-last'><a href='$_SERVER[PHP_SELF]?pageno=$nextpage'>Next</a> <a href='$_SERVER[PHP_SELF]?pageno=$this->total_pages'>Last</a></div>";
}
return $pageno;
}
// get first and back links
public function firstBack()
{
return $this->firstBack;
}
// get next and last links
public function nextLast()
{
return $this->nextLast;
}
// get where we are among pages
public function where()
{
return $this->where;
}
}
Use:
$pagination = new Pagination($dbh);
$pagination->totalRecords('SELECT COUNT(*) FROM `photos` WHERE `user` = :user', array(':user' => $_SESSION['id']));
$pagination->setLimit(12);
$pagination->page();
echo $pagination->firstBack();
echo $pagination->where();
echo $pagination->nextLast();
Result:
<div class='first-back'><a href='/xampp/web_development/new_study_2014/imagebox2016/app/public/test.php?pageno=1'>First</a> <a href='/xampp/web_development/new_study_2014/imagebox2016/app/public/test.php?pageno=3'>Back</a></div>
<div class='page-count'>(Page 4 of 6)</div>
<div class='next-last'><a href='/xampp/web_development/new_study_2014/imagebox2016/app/public/test.php?pageno=5'>Next</a> <a href='/xampp/web_development/new_study_2014/imagebox2016/app/public/test.php?pageno=6'>Last</a></div>
public function make_pagination()
{
$total = 0;
$query = "SELECT COUNT(downloads.dn_id) FROM downloads WHERE downloads.dn_type = 'audios'";
$stmt = $this->conn->prepare($query);
$stmt->execute();
$total = $stmt->fetchColumn();
//echo 'row_count = ' . $total;
// How many items to list per page
$limit = 11;
// How many pages will there be
$pages = ceil($total / $limit);
// What page are we currently on?
$page = min($pages, filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT, array(
'options' => array(
'default' => 1,
'min_range' => 1,
),
)));
// Calculate the offset for the query
$offset = ($page - 1) * $limit;
// Some information to display to the user
$start = $offset + 1;
$end = min(($offset + $limit), $total);
// The "back" link
$prevlink = ($page > 1) ? '« ‹' : '<span class="disabled">«</span> <span class="disabled">‹</span>';
// The "forward" link
$nextlink = ($page < $pages) ? '› »' : '<span class="disabled">›</span> <span class="disabled">»</span>';
// Display the paging information
echo '<div id="paging"><p>'.$prevlink.' Page '.$page.' of '.$pages. ' pages'. $nextlink.' </p></div>';
//prepare the page query
$query2 = "
SELECT * FROM downloads, map_artists, song_artists
WHERE map_artists.dn_id = downloads.dn_id
AND song_artists.artist_id = map_artists.artist_id
AND downloads.dn_type = 'audios' GROUP BY downloads.dn_id
ORDER BY downloads.dn_time DESC LIMIT :limit OFFSET :offset ";
$stmt2 = $this->conn->prepare($query2);
$stmt2->bindParam(':limit', $limit, PDO::PARAM_INT);
$stmt2->bindParam(':offset', $offset, PDO::PARAM_INT);
$stmt2->execute();
// Do we have any results?
if ($stmt2->rowCount() > 0) {
// Define how we want to fetch the results
$stmt2->setFetchMode(PDO::FETCH_ASSOC);
$iterator = new IteratorIterator($stmt2);
// Display the results
foreach ($iterator as $row) {
echo '<p>'. $row['dn_title'].' - '. $row['artist_name'].'</p>';
}
} else {
echo '<p>No results could be displayed.</p>';
}
}
Its Very possible that your SQL SELECT statement query may 1000 result into thousand of records. But its is not good idea to display all the results on one page. So we can divide this result into many pages as per requirement as pagination Class .
PAGINATE DATA WITH PAGINATION CLASS VERY EASY
pagination Class helps to generate paging
How To Use Pagination Class
visit this link for more info
http://utlearn.com/2017/02/15/pagination-class-use-pagination-class/
<?php
/**
* #package pagination class
* #version 1.0
*/
/*
#class Name: pagination
#Author: Ahmed Mohamed
#Version: 1.0
#Author URI: https://www.fb.com/100002349977660
#Website URI: http://www.utlearn.com
#class page URI: http://utlearn.com/2017/02/15/pagination-class-use-pagination-class
*/
include_once 'libs/config.php';
include_once 'libs/Database.php';
include_once 'libs/Model.php';
include_once 'libs/pagination.php';
if(!empty($_GET["page"]) and is_numeric($_GET["page"])){
$page = htmlspecialchars(strip_tags($_GET["page"]));
} else {
$page = 1;
}
// news = table name / you page URL / current page / true or false for full query
// its false i just use table name
$pag = new pagination("news", URL."?page=", 3, $page, false);
$pagination = $pag->pagination();
$data = $pag->data();
?>
<news>
<?php foreach($data as $news){ ?>
<header><h1><?=$news->title ?></h1> | <span><?=$news->date ?></span></header>
<div>
<?=$news->content ?>
</div>
<?php } ?>
</news>
<?=$pagination ?>