Accueil > > > [PHP5] LIMIT PACKAGE - LIMITATION GENERIQUE D'UN JEU DE RESULTAT - LES ITERATEURS EN PHP
[PHP5] LIMIT PACKAGE - LIMITATION GENERIQUE D'UN JEU DE RESULTAT - LES ITERATEURS EN PHP
Information sur la source
Description
Bon, encore des itérateurs ;-)
Ceci est un package tout simple, tout petit, permettant de renvoyer un jeu de résultat limité.
En clair, une requête, un tableau, vous n'en voulez qu'une partie ? ben voilà.
Ca rappelle le LIMIT de mysql évidemment.
Mais c'est plus pratique à mon sens.
Le fichier limit.php montre deux exemples d'utilisation simples.
Vous devez vous créer une base...
Nom : dbname
Table : table
champs : id
Ca suffit :-)
Ou adaptez à vos besoins, c'est très simple.
DB implémentées : mysql et mssql.
Et les tableaux...
Pratique pour faire une petite pagination facilement.
Source
- <?php
- /**
- * class oLimit implements Iterator
- * @author johan <johan.barbier@gmail.com>
- * @version 20061205
- */
- abstract class oLimit implements Iterator {
-
- /**
- * Number of items to retrieve
- *
- * @var integer
- */
- protected $iCount;
-
- /**
- * Starting offset
- *
- * @var integer
- */
- protected $iOffset;
-
- /**
- * Total number of items for the request
- *
- * @var unknown_type
- */
- protected $iMax;
-
- /**
- * Current internal position
- * @var integer
- */
- protected $iPos = 0;
-
- /**
- * Exception messages
- *
- */
- const ERROR_COUNT_EMPTY = 'iCount cannot be equal to 0';
- const ERROR_NO_INTEGER = 'iCount and iOffset parameters must be integer';
- const ERROR_NEGATIVE = 'iOffset cannot be negative';
-
- /**
- * Constructor
- * set some parameters
- *
- * @param integer $iOffset
- * @param integer $iCount
- */
- protected function __construct ($iOffset = 0, $iCount = -1) {
- if (!is_int ($iOffset) || !is_int ($iCount)) {
- throw new Exception (self::ERROR_NO_INTEGER);
- }
- if ($iOffset < 0) {
- throw new Exception (self::ERROR_NEGATIVE);
- }
- if ($iCount === 0) {
- throw new Exception (self::ERROR_COUNT_EMPTY);
- }
- $this -> iOffset = $iOffset;
- $this -> iCount = $iCount;
- $this -> iMax = $this -> countMax ();
- }
-
- /**
- * Iterator method
- * Moves the internal cursor to the next position
- *
- */
- public function next () {
- $this -> iPos ++;
- }
-
- /**
- * Iterator method
- * Checks the validity of the current position
- * If iCount === -1, then we go up to the end of the request (total number of items iMax)
- * If not, we check if the current position iPos is equal or greater than the number of items to retrieve (iCount)
- *
- * @return boolean
- */
- public function valid () {
- if (($this -> iOffset + $this -> iPos) > $this -> iMax) {
- return false;
- }
- if ($this -> iCount > -1 && $this -> iPos >= $this -> iCount) {
- return false;
- }
- return true;
- }
-
- /**
- * Returns the current internal position
- *
- * @return integer
- */
- public function getInternalPos () {
- return $this -> iPos;
- }
-
- /**
- * Returns the current request position
- *
- * @return integer
- */
- public function getExternalPos () {
- return $this -> iPos + $this -> iOffset;
- }
-
- /**
- * Returns the total number of items in the request
- *
- * @return integer
- */
- public function getExternalCount () {
- return $this -> iMax + 1;
- }
-
- abstract protected function countMax ();
- }
-
- /**
- * class mysqlLimit extends oLimit
- * @author johan <johan.barbier@gmail.com>
- * @version 20061205
- */
- class mysqlLimit extends oLimit {
-
- /**
- * request resource
- *
- * @var mysql result resource (comes from mysql_query)
- */
- private $rRes;
-
- /**
- * Exception messages
- *
- */
- const ERROR_NO_RESOURCE = 'rRes must be a valid mysql resource';
-
- /**
- * Constructor
- * Sets some parameters, and set the current position via data_seek
- *
- * @param mysql result resource $rRes
- * @param integer $iOffset
- * @param integer $iCount
- */
- public function __construct ($rRes, $iOffset = 0, $iCount = -1) {
- if (!is_resource ($rRes) || 'mysql result' !== get_resource_type ($rRes)) {
- throw new Exception (self::ERROR_NO_RESOURCE);
- }
- $this -> rRes = $rRes;
- parent::__construct ($iOffset, $iCount);
- mysql_data_seek ($this -> rRes, $this -> iOffset + $this -> iPos);
- }
-
- /**
- * Returns the current result array at the current position
- *
- * @return array
- */
- public function current () {
- return mysql_fetch_assoc ($this -> rRes);
- }
-
- /**
- * Checks validity of the current position
- *
- * @return boolean
- */
- public function valid () {
- return parent::valid ();
- }
-
- /**
- * Reset the resource result to the starting offset
- *
- */
- public function rewind () {
- mysql_data_seek ($this -> rRes, $this -> iOffset);
- }
-
- /**
- * Do not know what do return here
- *
- * @return void
- */
- public function key () {
- return false;
- //return mysql_fetch_assoc ($this -> rRes);
- }
-
- /**
- * Returns the total number of items of the query
- *
- * @return integer
- */
- protected function countMax () {
- return mysql_num_rows ($this -> rRes) - 1;
- }
- }
-
- /**
- * class mssqlLimit extends oLimit
- * see mysqlLimit for documentation
- * @author johan <johan.barbier@gmail.com>
- * @version 20061205
- */
- class mssqlLimit extends oLimit {
-
- private $rRes;
-
- const ERROR_NO_RESOURCE = 'rRes must be a valid mssql resource';
-
- public function __construct ($rRes, $iOffset = 0, $iCount = -1) {
- if (!is_int ($rRes) && (!is_resource ($rRes) || 'mssql result' !== get_resource_type ($rRes))) {
- throw new Exception (self::ERROR_NO_RESOURCE);
- }
- $this -> rRes = $rRes;
- parent::__construct ($iOffset, $iCount);
- mssql_data_seek ($this -> rRes, $this -> iOffset + $this -> iPos);
- }
-
- public function current () {
- return mssql_fetch_assoc($this -> rRes);
- }
-
- public function valid () {
- return parent::valid ();
- }
-
- public function rewind () {
- mssql_data_seek ($this -> rRes, $this -> iOffset);
- }
-
- public function key () {
- return false;
- //return mssql_fetch_assoc ($this -> rRes);
- }
-
- protected function countMax () {
- return mssql_num_rows ($this -> rRes) - 1;
- }
- }
-
- /**
- * class arrayLimit extends LimitIterator
- * @author johan <johan.barbier@gmail.com>
- * @version 20061205
- */
- class arrayLimit extends LimitIterator {
-
- /**
- * Exception messages
- *
- */
- const ERROR_NO_ARRAY = 'aRes must be an array';
-
- /**
- * Constructor
- * Sets some parameters and get LimitIterator constructor
- *
- * @param array $aRes
- * @param integer $iOffset
- * @param integer $iCount
- */
- public function __construct ($aRes, $iOffset = 0, $iCount = -1) {
- if (!is_array ($aRes)) {
- throw new Exception (self::ERROR_NO_ARRAY);
- }
- $aIt = new ArrayIterator ($aRes);
- parent::__construct ($aIt, $iOffset, $iCount);
- $this -> rewind ();
- }
- }
-
- /**
- * class LimitFactory
- * factory for the oLimit package (optional)
- * @author johan <johan.barbier@gmail.com>
- * @version 20061205
- */
- class LimitFactory {
-
- /**
- * Array of implemented oLimit classes
- *
- * @var array
- */
- private static $aTypes = array (
- 'MYSQL' => 'mysqlLimit',
- 'MSSQL' => 'mssqlLimit',
- 'ARRAY' => 'arrayLimit'
- );
-
- /**
- * Exception messages
- *
- */
- const ERROR_NO_VALID_TYPE = '{__TYPE__} is not a valid type';
- const ERROR_CLASS_NOT_FOUND = 'class {__CLASS__} has not been found';
-
- /**
- * Factory : get the correct object given an implemented oLimit class
- *
- * @param string $sType
- * @param mixed $mRes
- * @param integer $iOffset
- * @param integer $iCount
- * @return object
- */
- public static function factory ($sType, $mRes, $iOffset = 0, $iCount = -1) {
- if (!array_key_exists ($sType, self::$aTypes)) {
- throw new Exception (str_replace ('{__TYPE__}', $sType, self::ERROR_NO_VALID_TYPE));
- }
- if (!class_exists (self::$aTypes[$sType])) {
- throw new Exception (str_replace ('{__CLASS__}', self::$aTypes[$sType], self::ERROR_CLASS_NOT_FOUND));
- }
- return new self::$aTypes[$sType] ($mRes, $iOffset, $iCount);
- }
- }
- ?>
<?php
/**
* class oLimit implements Iterator
* @author johan <johan.barbier@gmail.com>
* @version 20061205
*/
abstract class oLimit implements Iterator {
/**
* Number of items to retrieve
*
* @var integer
*/
protected $iCount;
/**
* Starting offset
*
* @var integer
*/
protected $iOffset;
/**
* Total number of items for the request
*
* @var unknown_type
*/
protected $iMax;
/**
* Current internal position
* @var integer
*/
protected $iPos = 0;
/**
* Exception messages
*
*/
const ERROR_COUNT_EMPTY = 'iCount cannot be equal to 0';
const ERROR_NO_INTEGER = 'iCount and iOffset parameters must be integer';
const ERROR_NEGATIVE = 'iOffset cannot be negative';
/**
* Constructor
* set some parameters
*
* @param integer $iOffset
* @param integer $iCount
*/
protected function __construct ($iOffset = 0, $iCount = -1) {
if (!is_int ($iOffset) || !is_int ($iCount)) {
throw new Exception (self::ERROR_NO_INTEGER);
}
if ($iOffset < 0) {
throw new Exception (self::ERROR_NEGATIVE);
}
if ($iCount === 0) {
throw new Exception (self::ERROR_COUNT_EMPTY);
}
$this -> iOffset = $iOffset;
$this -> iCount = $iCount;
$this -> iMax = $this -> countMax ();
}
/**
* Iterator method
* Moves the internal cursor to the next position
*
*/
public function next () {
$this -> iPos ++;
}
/**
* Iterator method
* Checks the validity of the current position
* If iCount === -1, then we go up to the end of the request (total number of items iMax)
* If not, we check if the current position iPos is equal or greater than the number of items to retrieve (iCount)
*
* @return boolean
*/
public function valid () {
if (($this -> iOffset + $this -> iPos) > $this -> iMax) {
return false;
}
if ($this -> iCount > -1 && $this -> iPos >= $this -> iCount) {
return false;
}
return true;
}
/**
* Returns the current internal position
*
* @return integer
*/
public function getInternalPos () {
return $this -> iPos;
}
/**
* Returns the current request position
*
* @return integer
*/
public function getExternalPos () {
return $this -> iPos + $this -> iOffset;
}
/**
* Returns the total number of items in the request
*
* @return integer
*/
public function getExternalCount () {
return $this -> iMax + 1;
}
abstract protected function countMax ();
}
/**
* class mysqlLimit extends oLimit
* @author johan <johan.barbier@gmail.com>
* @version 20061205
*/
class mysqlLimit extends oLimit {
/**
* request resource
*
* @var mysql result resource (comes from mysql_query)
*/
private $rRes;
/**
* Exception messages
*
*/
const ERROR_NO_RESOURCE = 'rRes must be a valid mysql resource';
/**
* Constructor
* Sets some parameters, and set the current position via data_seek
*
* @param mysql result resource $rRes
* @param integer $iOffset
* @param integer $iCount
*/
public function __construct ($rRes, $iOffset = 0, $iCount = -1) {
if (!is_resource ($rRes) || 'mysql result' !== get_resource_type ($rRes)) {
throw new Exception (self::ERROR_NO_RESOURCE);
}
$this -> rRes = $rRes;
parent::__construct ($iOffset, $iCount);
mysql_data_seek ($this -> rRes, $this -> iOffset + $this -> iPos);
}
/**
* Returns the current result array at the current position
*
* @return array
*/
public function current () {
return mysql_fetch_assoc ($this -> rRes);
}
/**
* Checks validity of the current position
*
* @return boolean
*/
public function valid () {
return parent::valid ();
}
/**
* Reset the resource result to the starting offset
*
*/
public function rewind () {
mysql_data_seek ($this -> rRes, $this -> iOffset);
}
/**
* Do not know what do return here
*
* @return void
*/
public function key () {
return false;
//return mysql_fetch_assoc ($this -> rRes);
}
/**
* Returns the total number of items of the query
*
* @return integer
*/
protected function countMax () {
return mysql_num_rows ($this -> rRes) - 1;
}
}
/**
* class mssqlLimit extends oLimit
* see mysqlLimit for documentation
* @author johan <johan.barbier@gmail.com>
* @version 20061205
*/
class mssqlLimit extends oLimit {
private $rRes;
const ERROR_NO_RESOURCE = 'rRes must be a valid mssql resource';
public function __construct ($rRes, $iOffset = 0, $iCount = -1) {
if (!is_int ($rRes) && (!is_resource ($rRes) || 'mssql result' !== get_resource_type ($rRes))) {
throw new Exception (self::ERROR_NO_RESOURCE);
}
$this -> rRes = $rRes;
parent::__construct ($iOffset, $iCount);
mssql_data_seek ($this -> rRes, $this -> iOffset + $this -> iPos);
}
public function current () {
return mssql_fetch_assoc($this -> rRes);
}
public function valid () {
return parent::valid ();
}
public function rewind () {
mssql_data_seek ($this -> rRes, $this -> iOffset);
}
public function key () {
return false;
//return mssql_fetch_assoc ($this -> rRes);
}
protected function countMax () {
return mssql_num_rows ($this -> rRes) - 1;
}
}
/**
* class arrayLimit extends LimitIterator
* @author johan <johan.barbier@gmail.com>
* @version 20061205
*/
class arrayLimit extends LimitIterator {
/**
* Exception messages
*
*/
const ERROR_NO_ARRAY = 'aRes must be an array';
/**
* Constructor
* Sets some parameters and get LimitIterator constructor
*
* @param array $aRes
* @param integer $iOffset
* @param integer $iCount
*/
public function __construct ($aRes, $iOffset = 0, $iCount = -1) {
if (!is_array ($aRes)) {
throw new Exception (self::ERROR_NO_ARRAY);
}
$aIt = new ArrayIterator ($aRes);
parent::__construct ($aIt, $iOffset, $iCount);
$this -> rewind ();
}
}
/**
* class LimitFactory
* factory for the oLimit package (optional)
* @author johan <johan.barbier@gmail.com>
* @version 20061205
*/
class LimitFactory {
/**
* Array of implemented oLimit classes
*
* @var array
*/
private static $aTypes = array (
'MYSQL' => 'mysqlLimit',
'MSSQL' => 'mssqlLimit',
'ARRAY' => 'arrayLimit'
);
/**
* Exception messages
*
*/
const ERROR_NO_VALID_TYPE = '{__TYPE__} is not a valid type';
const ERROR_CLASS_NOT_FOUND = 'class {__CLASS__} has not been found';
/**
* Factory : get the correct object given an implemented oLimit class
*
* @param string $sType
* @param mixed $mRes
* @param integer $iOffset
* @param integer $iCount
* @return object
*/
public static function factory ($sType, $mRes, $iOffset = 0, $iCount = -1) {
if (!array_key_exists ($sType, self::$aTypes)) {
throw new Exception (str_replace ('{__TYPE__}', $sType, self::ERROR_NO_VALID_TYPE));
}
if (!class_exists (self::$aTypes[$sType])) {
throw new Exception (str_replace ('{__CLASS__}', self::$aTypes[$sType], self::ERROR_CLASS_NOT_FOUND));
}
return new self::$aTypes[$sType] ($mRes, $iOffset, $iCount);
}
}
?>
Historique
- 04 décembre 2006 17:30:10 :
- Modifs mineures sur le package + ajout d'un exemple basique de pager utilisant ce package.
- 05 décembre 2006 17:39:47 :
- Optimisation (j'ai viré des trucs inutiles)
Sources du même auteur
Sources de la même categorie
Commentaires et avis
Discussions en rapport avec ce code source dans le forum
Requete SQL et Array [ par dadybond ]
Bonjour,Je voudrais savoir si il est possible de faire une requete SQL qui selectionne tous les resultat sauf ceux qui sont contenus dans un tableau (
Problème array et str_replace [ par Tilix ]
Salut $sql = 'SELECT contenu FROM cagnote ORDER BY id DESC' ; $req = mysql_query($sql) or die('Erreur SQL !<br>'.$sql.'<br>'.mysql_error(
webmail affichage par page des emails [ par astyax ]
Salut à tous,voilà, je suis toujours en train de construire mon webmail et j'aimerai savoir comment on fait pour faire un affichage par page. Autant a
problème avec requete sql [ par darkwisk ]
Salut à tous,Voilà mon problème.....J'ai 2 tables dans ma base, La 1ère "maisons" La 2ème "clients"Je voudr
Array & MySQl [ par boulika ]
BonjourJe dois faire une petit programme avec des données de mysql :je dois récupérer des infos d'une base de données mais de deux tables :$db = mysql
recuperer une requete sql dans un array [ par stef1589 ]
bonjour à tousje souhaiterais récuperer la table "config" d'une requete mysql dans un array:$requete = mysql_query("SELECT * FROM config");mais apres
Restauration BBD ne fonctionne pas [ par LiTtLeBuBu ]
Bonjour,Voila j'ai récupérer un script sur le site pour sauvegarder ma BDD. J'ai modifié le script pour enlever les fonctions envoi par mail et FTP. J
Enregistrer des résultats ARRAY dans des variables séparée... [ par Sniark ]
Bonjour à tous,Dans un formulaire, j'ai des SELECT multiple sous forme de listes, dont le contenu est le résultat d'une requête sur ma base de données
sql dans un array [ par Alpha911 ]
Bonjour, J'ai parcouru les aides sur les forums mais ce n'est pas tres clair pour moi. Je dispose d'une base de donnée dans laquelle se trouve des ad
Array SQL [ par OneHacker ]
Bonjour, je sais pas comment afficher un tableau SQL :while($data = mysql_fetch_array($req)) { // on affiche les informations de l'enregistreme
|
Derniers Blogs
IMAGINE CUP 2012, MAKE A SIGN EN FINALEIMAGINE CUP 2012, MAKE A SIGN EN FINALE par junarnoalg
Voilà qui est fait, la nouvelle est officielle ! L'équipe belge "Make a Sign" va au pays des kangourous défendre son projet dans la catégorie Software Design. http://www.imaginecup.com/CompetitionsContent/Competition/WorldwideFinalists.aspx V...
Cliquez pour lire la suite de l'article par junarnoalg KINECT 1.5 IS OUT !KINECT 1.5 IS OUT ! par Vko
La version 1.5 du Kinect For Microsoft vient tout juste de sortir ! Plein de nouveautés: Tracking de squelette en Near Mode Détection en position assise Détection faciale avec un SDK dédié Documentation et des guideline (enfin) Un out...
Cliquez pour lire la suite de l'article par Vko LES ACTUALITéS DE LA SEMAINE SUR C2I.FR (14 MAI - 20 MAI) LES ACTUALITéS DE LA SEMAINE SUR C2I.FR (14 MAI - 20 MAI) par richardc
Mise à jour des Web API du 14 Mai
Réservez dès maintenant votre journée du 20 juin pour le Windows Azure Dev Camp 2012 à Paris
Mise à jour de Team Foundation Service
MechCommander 2 sur Windows 8
Entity Framework 5 Release Candidate e...
Cliquez pour lire la suite de l'article par richardc REACTIVE EXTENSIONS : CONSOMMER DES SERVICES AVEC RX PARTIE 3, LES PIèGES à éVITERREACTIVE EXTENSIONS : CONSOMMER DES SERVICES AVEC RX PARTIE 3, LES PIèGES à éVITER par Groc
Une mauvaise utilisation de rx lors de l'écriture d'une couche d'accès à des services peut conduire à des cas embarassants avec des erreurs mal gérées, des appels qui ne partent lorsqu'ils le devraient, et même des résultats incorrects . le tout nuis...
Cliquez pour lire la suite de l'article par Groc SHAREPOINT BLOG SITE, PROBLèME D'ARCHIVESSHAREPOINT BLOG SITE, PROBLèME D'ARCHIVES par junarnoalg
Dernièrement, nous avons migré le site
myTIC
vers un nouveau serveur SharePoint 2010. Dans les contenus que nous vouloins récupérer, nous avions un certain nombre de blogs.
Nous avons utilisé les commandes Power...
Cliquez pour lire la suite de l'article par junarnoalg
Logiciels
sDEVIS-FACTURES vlPRO (8.1.0.3)SDEVIS-FACTURES VLPRO (8.1.0.3)sDEVIS-FACTURES vlPRO a été mis au point pour les particuliers, créateurs, entrepreneurs, artisa... Cliquez pour télécharger sDEVIS-FACTURES vlPRO 974 Application Server (12.2.4.6)974 APPLICATION SERVER (12.2.4.6)Développez de puissantes applications dans un environnement de 'cloud computing', clusterisé, séc... Cliquez pour télécharger 974 Application Server vPicture (1.4.2.1)VPICTURE (1.4.2.1)Avec vPicture, hébergez vos images facilement et rapidement.
vPicture est un utilitaire simple, ... Cliquez pour télécharger vPicture Easy-Planning (2.2.1.6)EASY-PLANNING (2.2.1.6)Easy-Planning permet de créer des plannings sous la représentation de diagrammes et est adapté au... Cliquez pour télécharger Easy-Planning COM-BACKUP (2.0)COM-BACKUP (2.0)
COM-BACKUP est un logiciel de sauvegarde qui permet de planifier les sauvegardes de vos dossiers ...
Cliquez pour télécharger COM-BACKUP
|