Pagina 1 di 3 1 2 3 ultimoultimo
Visualizzazione dei risultati da 1 a 10 su 22
  1. #1

    [ PILLOLA ] Impaginiamo i risultati di MySQL con le OOP

    Ho visto tanti 3d aperti con tantissimi post per risolvere il problema della paginazione.

    Con questa classe dovreste trovare tutto molto semplice:

    Cosa serve?
    Solo il file che chiameremo php.sql.pager.class (nome indicativo) con questo contenuto:
    Codice PHP:
    class _makePager {

     var 
    $limit;
     var 
    $page;
     var 
    $numPages;
     var 
    $offset;
     var 
    $sql;
     var 
    $menu;

     function 
    _makePager $limit ) {

      
    $this->limit $limit;

     }

     function 
    _getPagerData $numHits$page ) {

      
    $numHits = (int) $numHits;
      
    $this->limit max((int) $this->limit1);
      
    $this->page = (int) $page;
      
    $this->numPages ceil($numHits $this->limit);
      
    $this->page max($this->page1);
      
    $this->page min($this->page$this->numPages);
      
    $this->offset = ($this->page 1) * $this->limit;
      
    $this->sql " LIMIT ".$this->offset.", ".$this->limit;
      
    $this->_makeMenu();

     }

     function 
    _makeMenu () {

      if (
    $this->numPages>1) {

       if (
    $this->page>1$this->menu['PREVIOUS'] = ($this->page-1);

       for (
    $i=1$i<=$this->numPages$i++) {
        if (
    $i == $this->page$this->menu['PAGES'][] = array (
                                   
    'ID'     => $i,
                                   
    'STATUS' => false
                                  
    );
        else 
    $this->menu['PAGES'][] = array (
                         
    'ID'     => $i,
                         
    'STATUS' => true
                        
    );
       }

       if (
    $this->page<$this->numPages$this->menu['NEXT'] = ($this->page+1);

      }

     }

     function 
    _getUri $_pagevar ) {

      
    $_getvars $_SERVER["QUERY_STRING"];
      
    $_url $_SERVER["PHP_SELF"]."?";
      
    $_getvars explode"&"$_getvars );

      for (
    $i=0$i!=count($_getvars); $i++) {
       list (
    $key$value) = explode"="$_getvars[$i] );
       if ((
    $key)&&($value)) if ($key!=$_pagevar$_url.= "{$key}={$value}&amp;";
      }

      return 
    "{$_url}{$_pagevar}=";

     }


    Nel prossimo post vedremo come funziona!
    [ DarCas The Architect ]
    [ The DarCas Of Blog ]
    Chuck Norris riesce a trovare un pagliaio dentro a un ago
    :maLOL:

  2. #2

    Come utilizzare la classe

    Facciamo un caso tipo:
    Abbiamo una pagina che ri chiama result.php che contiene la lista di iscritti ad un forum.
    Diciamo che ne vogliamo visualizzare 20 per pagina.
    Per cambiare pagina di visualizzazione si passerà il solo parametro GET p.

    Allora il codice sarà:
    Codice PHP:
    require_once("php.sql.pager.class");
    $_PAGER = new _makePager(20);

    $_sql mysql_query("SELECT COUNT(*) FROM user_forum");
    $_PAGER _getPagerData(mysql_result($_sql),$_GET[p]);

    $_sql mysql_query("SELECT * FROM user_forum ORDER BY UserName {$_PAGER->sql}");
    while (
    $row mysql_fetch_row($_sql)) {
     
    // STAMPO I RISULTATI

    a questo punto avrò un altro oggetto della classe che conterrà i dati per fare il menu di navigazione, con tutte le pagine e con due dati per creare la pagina PRECEDENTE e SUCCESSIVA.

    Nel prossimo post vedremo come realizzare il menu.
    [ DarCas The Architect ]
    [ The DarCas Of Blog ]
    Chuck Norris riesce a trovare un pagliaio dentro a un ago
    :maLOL:

  3. #3

    Come creare il menu di navigazione

    Dunque, cominciamo subito col dire che ho realizzato questo sistema, perchè è quello più elastico e personalizzabile, visto che il mio designer mi crea sempre menu di navigazione fantascentifici e stare ogni volta a fare funzioni personalizzate era al quanto dispendioso in termini di tempo.

    Tornando al nostro esempio avremo un oggetto che si chiama $_PAGER->menu che è un array con la seguente struttura:
    codice:
    array (
           PREVIOUS => (int),
           PAGES    => array (
                              ID     => (int),
                              STATUS => (bool) 
                       ),
           NEXT     => (int)
    )
    forse ad intuito riuscite già a capire come funziona, ad ogni modo vi spiego col solito esempio.

    Sempre nella stessa mettiamo una barra mooolto grezza:
    Codice PHP:
    if ($_PAGER->menu['PREVIOUS']) echo "<a href=\"".$_PAGER->_getUri("p").$_PAGER->menu['PREVIOUS']."\">pagina precedente</a>";

    $_PGS $_PAGER->menu['PAGES'];
    for (
    $j=0$j!=count($_PGS); $j++) {

     if (
    $_PGS[$j]['STATUS']) echo " [ <a href=\"".$_PAGER->_getUri("p").$_PGS[$j]['ID']."\">{$_PGS[$j]['ID']}</a> ] ";
     else echo 
    $_PGS[$j]['ID'];

    }

    if (
    $_PAGER->menu['NEXT']) echo "<a href=\"".$_PAGER->_getUri("p").$_PAGER->menu['NEXT']."\">pagina successiva</a>"
    facile no?
    Questa è ora una pagina molto grossolana, ma si può gestire grafica molto complessa (l'ho fatto io personalmente) e con pochi if come abbiamo potuto vedere.

    Ah dimenticavo,
    l'oggetto $_PAGER->_getUri("p") che forse avrete notato nella creazione dell'url, serve semplicemente a ricostruire anche complesse url formate da tante variabili GET, senza ovviamente la variabile utilizzata per cambiare pagina e che viene specificata al momento della chiamata all'oggetto.

    Beh, questo è quanto, spero sia utile..
    Poi appena ho altro tempo vi passo altre classi che ho..

    [ DarCas The Architect ]
    [ The DarCas Of Blog ]
    Chuck Norris riesce a trovare un pagliaio dentro a un ago
    :maLOL:

  4. #4
    Sto cercando di usare la pillola ma con POSTGRESQL: ho cambiato nella classe la funzione _getPagerData

    function _getPagerData ( $numHits, $page ) {
    $numHits = (int) $numHits;
    $this->limit = max((int) $this->limit, 1);
    $this->page = (int) $page;
    $this->numPages = ceil($numHits / $this->limit);
    $this->page = max($this->page, 1);
    $this->page = min($this->page, $this->numPages);
    $this->offset = ($this->page - 1) * $this->limit;
    $this->sql = " LIMIT ".$this->limit." OFFSET ".$this->offset;
    $this->_makeMenu();
    }

    per adattarla alla sintassi
    SELECT * FROM TABELLA LIMIT n OFFSET m

    ma non riesco a far andare il codice seguente:

    <?
    require_once("php.sql.pager.class");
    //includo il file di configurazione
    require_once("config.inc.php");
    $dbconn = pg_connect ($postgres) or die ("BABA");
    $_PAGER = new _makePager(3);
    $_sql=pg_query($dbconn,"SELECT COUNT(*) FROM \"FOTO\";");
    echo "1";
    $_PAGER = _getPagerData(pg_fetch_result($_sql),$_GET["p"]);
    echo "2";
    $_sql = pg_query($dbconn,"SELECT * FROM \"FOTO\" {$_PAGER->sql};");
    echo "3";
    while ($row = pg_fetch_row($_sql, $i))
    {
    for ($j=0; $j < count($row); $j++) {
    echo "$row[$j]";
    }
    echo "
    ";
    }
    ?>
    che si ferma senza dare alcun errore stampando solo 1, cioè alla chiamta alla funzione _getPagerData. Ho sostituito l'analogo mysql_result con pg_fetch_result che dovrebbe essere analoga, per cui non capisco cosa fare. :master:

  5. #5
    Quella classe funziona a prescidere dal db, visto che gestisce semplicemente i risultati e crea la LIMIT, che fa parte dei comendi SQL..

    Inoltre non conosco la corretta sintassi per il db che utilizzi tu..
    Controlla che il OFFSET faccia esattamente quello che fa la contro parte mysql.

    In pratica in mysql facendo
    LIMITI X,Y
    dici: Comincia dal risultato numero X e stampamene (se ci sono) Y
    [ DarCas The Architect ]
    [ The DarCas Of Blog ]
    Chuck Norris riesce a trovare un pagliaio dentro a un ago
    :maLOL:

  6. #6
    In PostgresSQL la clausola limit diventa come ti dicevo

    LIMIT numero_record OFFSET a_partire_da_quale record

    per cui l'avevo adattata come sopra. Credo perciò che il problema sia nella funzione pg_fetch_result che non da un argomento corretto alla funzione _getPagerData. Il parametro $numHits che tale funzione prende è un intero che indica il numero totale di record o sbaglio? Grazie mille

  7. #7
    Originariamente inviato da abmcr
    In PostgresSQL la clausola limit diventa come ti dicevo

    LIMIT numero_record OFFSET a_partire_da_quale record

    per cui l'avevo adattata come sopra. Credo perciò che il problema sia nella funzione pg_fetch_result che non da un argomento corretto alla funzione _getPagerData. Il parametro $numHits che tale funzione prende è un intero che indica il numero totale di record o sbaglio? Grazie mille
    Esatto,
    $numHits indica il numero totale di risultati...

    La modifica che hai apportato è corretta, controlla se pg_fetch_result restituisce quanto ti aspetti... magari accanto a pg_fetch_array() mettici
    Codice PHP:
    or die ("ERRORE"
    magari cominci ad isolare il problema!
    [ DarCas The Architect ]
    [ The DarCas Of Blog ]
    Chuck Norris riesce a trovare un pagliaio dentro a un ago
    :maLOL:

  8. #8

  9. #9
    Scusami tanto: provando con Mysql , ho fatto questo

    <?
    include_once("include/config.php");
    require_once("php.pager.class.php");

    $_PAGER = new _makePager(8);
    $_sql = mysql_query("SELECT COUNT(*) FROM PI_LINK");
    $_PAGER = _getPagerData(mysql_result($_sql),$_GET["p"]);

    $_sql = mysql_query("SELECT * FROM PI_LINK ORDER BY ID {$_PAGER->sql}");
    while ($row = mysql_fetch_row($_sql)) {

    echo $row[2]."
    ";

    }
    ?>

    che però mi dice

    Fatal error: Call to undefined function: _getpagerdata() in /var/www/vhost/portaleitalia/pippo.php on line 7
    cioè dove si chiama _getPagerData

    Ho fatto un mero copia incolla. Ma :master:

  10. #10
    se mi e' possibile vorrei aggiungere un metodo facile facile per fare una semplice impaginazione con i link first, prev, next e last, in questo esempio con filtro pagina per evitare di clickare inutilmente, ad esempio, last quando siamo gia' a last, o next, etc. etc.

    codice:
    <?php
    class SimplePaginator {
    
    	var $first = 0;
    	var $last = 0;
    	var $prev = 0;
    	var $next = 0;
    	var $limit = 0;
    
    	function SimplePaginator( &$limit, &$page, &$rows ) {
    	        $limit = (int) $limit;
    		$page = (int) $page;
    		$rows = (int) $rows;
    		$this->last = &ceil( $rows / $limit );
    		if( $page > $this->last || $page < 1 ) {
    			$page = 1;
    		}
    		if( $page < $this->last ) {
    			$this->next = $page + 1;
    		}
    		if( $page > 1 ) {
    			$this->prev = $page - 1;
    			$this->first = 1;
    		}
    		$this->limit = ( $page - 1 ) * $limit;
    	}
    }
    
    
    // QUAMNTI RECORDS ALLA VOLTA VOGLIO MOSTRARE ?
    $daMostrare = 5;
    
    // IN QUALE PAGINA MI TROVO ?
    $pagina = isSet( $_GET['page'] ) == true ? (int)$_GET['page'] : 1;
    
    // QUANTI RECORDS IN TOTALE HO NEL DATABASE ?
    // ( in questo caso non passo il risultato da db ma lo imposto a mano )
    $totaleInDatabase = 13;
    
    
    
    
    // OGGETTO PAGINA
    $page = &new SimplePaginator( $daMostrare, $pagina, $totaleInDatabase );
    
    
    
    
    // ESEMPIO IN HTML
    // ( controlo che i valori siano diversi da 0 e dalla pagina corrente )
    $output = '';
    if( $pagina != $page->first && $page->first !== 0 ) {
    	$output .= '&lt;&lt; &amp;nbsp; ';
    }
    else {
    	$output .= '&lt;&lt; &amp;nbsp; ';
    }
    if( $pagina != $page->prev && $page->prev !== 0 ) {
    	$output .= '&lt; &amp;nbsp; ';
    }
    else {
    	$output .= '&lt; &amp;nbsp; ';
    }
    $output .= ''.$pagina.' / '.$page->last.'  ';
    if(  $pagina != $page->next && $page->next !== 0 ) {
    	$output .= '&gt; &amp;nbsp; ';
    }
    else {
    	$output .= '&gt; &amp;nbsp; ';
    }
    if(  $pagina != $page->last && $page->last !== 0 ) {
    	$output .= '&gt;&gt; &amp;nbsp; ';
    }
    else {
    	$output .= '&gt;&gt; &amp;nbsp; ';
    }
    echo $output;
    
    
    
    // ESEMPIO QUERY
    echo '<hr />SELECT * FROM tabella LIMIT '.$page->limit.', '.$daMostrare.'
      
    ';
    
    
    
    // ESEMPIO RISULTATI
    $row = 0;
    $start = $page->limit;
    while( $start < $totaleInDatabase && $row < $daMostrare ) {
    	echo 'risultato '.$row.' della query
    ';
    	$start++;
    	$row++;
    }
    ?>
    magari torna utile a qualcuno
    Formaldehyde a new Ajax PHP Zero Config Error Debugger

    WebReflection @WebReflection

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2025 vBulletin Solutions, Inc. All rights reserved.