2011-12-02 9 views
14
$objConnect = mysql_connect("localhost","root","") or die(mysql_error()); 
$objDB = mysql_select_db("Test"); 

$strSQL = "SELECT * FROM UserAddedRecord WHERE (Name LIKE '%".$getname."%' and State LIKE '%".$getstate."%' and Cell LIKE '%".$getcell."%' and Custgroup LIKE '%".$getgroup."%') AND user_id=$id"; 

$objQuery = mysql_query($strSQL) or die ("Error Query [".$strSQL."]"); 
$Num_Rows = mysql_num_rows($objQuery); 

$Per_Page = 5; 

if (!isset($_GET['Page'])) { 
    $Page = 1; 
} else { 
    $Page = $_GET['Page']; 
} 

$Prev_Page = $Page - 1; 
$Next_Page = $Page + 1; 

$Page_Start = (($Per_Page * $Page) - $Per_Page); 
if ($Num_Rows <= $Per_Page) { 
    $Num_Pages = 1; 
} elseif (($Num_Rows % $Per_Page) == 0) { 
    $Num_Pages = ($Num_Rows/$Per_Page) ; 
} else { 
    $Num_Pages = ($Num_Rows/$Per_Page) + 1; 
    $Num_Pages = (int) $Num_Pages; 
} 


$strSQL .=" order by addedrec_ID DESC LIMIT $Page_Start , $Per_Page"; 
$objQuery = mysql_query($strSQL) or trigger_error(mysql_error());; 

if ($Prev_Page) { 
    echo " <a href ='$_SERVER[SCRIPT_NAME]?Page=$Prev_Page&txtName=$getname&txtState=$getstate&txtCell=$getcell&txtGroup=$getgroup'><< Back</a> "; 
} 

for ($i=1; $i <= $Num_Pages; $i++) { 
    if ($i != $Page) { 
     echo " <a href ='$_SERVER[SCRIPT_NAME]?Page=$i&txtName=$getname&txtState=$getstate&txtCell=$getcell&txtGroup=$getgroup'>$i</a> "; 
    } else { 
     echo "<b> $i </b>"; 
    } 
} 

if ($Page!=$Num_Pages) { 
    echo " <a href ='$_SERVER[SCRIPT_NAME]?Page=$Next_Page&txtName=$getname&txtState=$getstate&txtCell=$getcell&txtGroup=$getgroup'>Next>></a> ";   
} 

mysql_close($objConnect); 

Este es el código que utilizo para crear la página de paginación para los datos search.But Me acabo de dar cuenta de que no tengo demasiados registros entonces tendrá demasiados numbers.I'm página de tratar de limitar la número de página que se muestra, y busque muchos ejemplos ... hay muchas formas de hacerlo, pero todavía no tengo idea de cómo limitarlo para mi método ...límite de número de página de la paginación

Respuesta

28

Ok si te refieres a mostrar algo como

Prev 1 2 3 4 5 6 .. 40 41 Next 
Prev 1 2 .. 6 7 8 9 10 .. 40 41 Next 

Lo primero que necesitamos es crear una función que puede procesar lo que necesitamos para producir la paginación. Aquí hay una función que uso y funciona bien.

function get_paging_info($tot_rows,$pp,$curr_page) 
{ 
    $pages = ceil($tot_rows/$pp); // calc pages 

    $data = array(); // start out array 
    $data['si']  = ($curr_page * $pp) - $pp; // what row to start at 
    $data['pages']  = $pages;     // add the pages 
    $data['curr_page'] = $curr_page;    // Whats the current page 

    return $data; //return the paging data 

} 

Ahora esta función es bastante sólido y funciona muy bien para mí.

Así se pasa esta función

  • $ tot_rows = contado filas para Llamar número de
  • $ pp = elementos por página
  • $ curr_page = la página actual

Ok, ahora que tiene los datos que necesita, tendrá que mostrarlo.

Esto es lo que uso y por favor leí antes de pensar, 'ah, es demasiado larga'. En realidad es muy simple.

Heres una instantánea de lo que volverá

enter image description here

<!-- Create the query --> 
    <?php $count = mysql_fetch_assoc(mysql_query ("SELECT COUNT(rows) as count FROM table")) ; 

    <?php $count = $count[0]['count']; ?> 

<!-- Call our function from above --> 
<?php $paging_info = get_paging_info($count,5,34); ?> 


<p> 
    <!-- If the current page is more than 1, show the First and Previous links --> 
    <?php if($paging_info['curr_page'] > 1) : ?> 
     <a href='' title='Page 1'>First</a> 
     <a href='' title='Page <?php echo ($paging_info['curr_page'] - 1); ?>'>Prev</a> 
    <?php endif; ?> 



    <?php 
     //setup starting point 

     //$max is equal to number of links shown 
     $max = 7; 
     if($paging_info['curr_page'] < $max) 
      $sp = 1; 
     elseif($paging_info['curr_page'] >= ($paging_info['pages'] - floor($max/2))) 
      $sp = $paging_info['pages'] - $max + 1; 
     elseif($paging_info['curr_page'] >= $max) 
      $sp = $paging_info['curr_page'] - floor($max/2); 
    ?> 

    <!-- If the current page >= $max then show link to 1st page --> 
    <?php if($paging_info['curr_page'] >= $max) : ?> 

     <a href='' title='Page 1'>1</a> 
     .. 

    <?php endif; ?> 

    <!-- Loop though max number of pages shown and show links either side equal to $max/2 --> 
    <?php for($i = $sp; $i <= ($sp + $max -1);$i++) : ?> 

     <?php 
      if($i > $paging_info['pages']) 
       continue; 
     ?> 

     <?php if($paging_info['curr_page'] == $i) : ?> 

      <span class='bold'><?php echo $i; ?></span> 

     <?php else : ?> 

      <a href='' title='Page <?php echo $i; ?>'><?php echo $i; ?></a> 

     <?php endif; ?> 

    <?php endfor; ?> 


    <!-- If the current page is less than say the last page minus $max pages divided by 2--> 
    <?php if($paging_info['curr_page'] < ($paging_info['pages'] - floor($max/2))) : ?> 

     .. 
     <a href='' title='Page <?php echo $paging_info['pages']; ?>'><?php echo $paging_info['pages']; ?></a> 

    <?php endif; ?> 

    <!-- Show last two pages if we're not near them --> 
    <?php if($paging_info['curr_page'] < $paging_info['pages']) : ?> 

     <a href='<?php echo str_replace('/page'.$paging_info['curr_page'], '', $paging_info['curr_url']) . '/page'.($paging_info['curr_page'] + 1); ?>' title='Page <?php echo ($paging_info['curr_page'] + 1); ?>'>Next</a> 

     <a href='<?php echo str_replace('/page'.$paging_info['curr_page'], '', $paging_info['curr_url']) . '/page'.$paging_info['pages']; ?>' title='Page <?php echo $paging_info['pages']; ?>'>Last</a> 

    <?php endif; ?> 
</p> 
+0

Muchas gracias por su ejemplo y todas las instrucciones, ahora estoy tratando de comprenderlo y aprenderlo. –

+0

Me alegra ayudar. Obviamente, acabo de tomar esto de mi código y lo alteré un poco, pero la estructura está ahí, para que juegues. –

+1

El problema con este tipo de navegación de página es que puede ser difícil llegar a las páginas en el medio de un rango '...' (al menos haciendo clic). Puede considerar usar el enfoque que describo en [esta pregunta] (http://stackoverflow.com/q/7835752/999120), que permite un acceso fácil a cualquier página en unos pocos clics de mouse, incluso cuando hay miles de páginas. – Doin

2

Deberá usar una cláusula LIMIT en su declaración sql. Por ejemplo:

SELECT <column> 
    FROM <table> 
    LIMIT 0, 5 

Referencia: SELECT Syntax

+0

Gracias por su respuesta.Es esta fila? '$ StrSQL. =" Orden por addedrec_ID DESC LIMIT $ Page_Start, $ Per_Page "; ' –

+0

Consulte este http://php.about.com/od/mysqlcommands/g/Limit_sql.htm – Cyclonecode

2

He resuelto un problema muy similar a otra persona con un guión muy similar aquí: How to limit pages shown in pagination script

Además, he notado algunas otras anomalías con la secuencia de comandos (Además del formato ilegible que me fijo). Debe cambiar todas las apariciones de $_SERVER[SCRIPT_NAME]-$_SERVER['SCRIPT_NAME']. En la secuencia de comandos, por ejemplo:

echo " <a href ='$_SERVER[SCRIPT_NAME]?Page=..."; 

se convertiría en:

echo " <a href ='{$_SERVER['SCRIPT_NAME']}?Page=..."; 
+0

Gracias por su enlace y corrección, lo voy a probar ahora. –

2

mi código siempre muestran al menos 9 páginas en el caso de todas las páginas> 9 lo que está en la página 1,2,3

<ul class="pagination pagination-sm" style="align:center"> 
    <li><a href="./?page=1"><</span></a></li> 
    <?php 
    if ($current_page <4){ 
     if ($total_pages<9) 
     { 
      for($i = 1; $i <= $total_pages; $i++) 
      { 

       if ($i == $current_page) 
       { 
        echo '<li class="active"><a href="#">'; echo $i.'</a></li>'."\n"; 
       } else { 
        echo ' <li><a href="./?page='.$i.'">'; echo $i.'</a></li>'."\n"; 
       } 
      } 
     } 
     else 
     { 
      for($i = 1; $i <= 9; $i++) 
      { 

       if ($i == $current_page) 
       { 
        echo '<li class="active"><a href="#">'; echo $i.'</a></li>'."\n"; 
       } else { 
        echo ' <li><a href="./?trang='.$i.'">'; echo $i.'</a></li>'."\n"; 
       } 
      } 
     } 
    } 
    elseif ($current_page >$total_pages-4) 
    { 
     if ($total_pages<9) 
     { 
      for($i = 1; $i <= $total_pages; $i++){ 

       if ($i == $current_page){ 
        echo '<li class="active"><a href="#">'; echo $i.'</a></li>'."\n"; 
       } else { 
        echo ' <li><a href="./?page='.$i.'">'; echo $i.'</a></li>'."\n"; 
       } 
      } 
     }else{ 
      for($i = $total_pages-8; $i <= $total_pages; $i++){ 

       if ($i == $current_page){ 
        echo '<li class="active"><a href="#">'; echo $i.'</a></li>'."\n"; 
       } else { 
        echo ' <li><a href="./?page='.$i.'">'; echo $i.'</a></li>'."\n"; 
       } 
      } 
     } 

    }else{ 
     for($i = max(1, $current_page - 4); $i <= min($current_page + 4, $total_pages); $i++){ 

      if ($i == $current_page){ 
       echo '<li class="active"><a href="#">'; echo $i.'</a></li>'."\n"; 
      } else { 
       echo ' <li><a href="./?trang='.$i.'">'; echo $i.'</a></li>'."\n"; 
      } 
     } 
    } 
    ?> 
    <li> 
     <a href="./?trang=<?php echo $total_pages ?>">></a> 
    </li> 
</ul> 
1

propósito de este código es sólo para mostrar (cierta) número determinado de páginas en la paginación

Obtener número de página actual de URL y definir $curr_pg_numb

obtener el número de páginas totales a partir de MySQL y definir $total_pages

Y aquí es el código de la paginación

$counter=0; 
$init_num_to_left = 3;//initial number of pages to show to left from current page 
$init_num_to_right = 4; 

if($curr_pg_numb - $init_num_to_left < 1){ 
$init_num_to_right = $init_num_to_right + (1 - ($curr_pg_numb - $init_num_to_left)); 
$init_num_to_left = $curr_pg_numb - 1; 
} 
else if($curr_pg_numb + $init_num_to_right > $total_pages){ 
$init_num_to_left = $init_num_to_left + (($curr_pg_numb + $init_num_to_right) - $total_pages); 
$init_num_to_right = ($curr_pg_numb + $init_num_to_right) - $total_pages; 
} 

while($counter <= $total_pages) { 
    if ($counter > 0){ 
    if ($curr_pg_numb==$counter){ 
    echo '<strong> '. (htmlspecialchars($curr_pg_numb , ENT_QUOTES, "UTF-8") + 0). '</strong> '; 
    } 
    else { 
    if ($counter >= ($curr_pg_numb - $init_num_to_left) and $counter <= ($curr_pg_numb + $init_num_to_right)) { 
    echo '<a href="?cpn='. htmlspecialchars(($counter), ENT_QUOTES, "UTF-8"). '" style="margin:5px;">'. htmlspecialchars(($counter), ENT_QUOTES, "UTF-8"). '</a>'; 
    } 
    }//else { 
    }//if ($counter > 0){ 
$counter++; 
}//while($counter <= $total_pages) { 
3

$ count_pages = ceil ($ Total/$ items_per_page);

2

que sea sencillo, aquí está el código:

<?php  
    //put this code on the begining of the page 
    $page=$_GET['page']; //Getting page number from url | example: www.mydomain.com/index.php?page=3 
    if(!is_numeric($page)) $page=1; //If there is no page number specified we set number 1 
$queryCount = "SELECT * FROM table "; //select from db 
$query = $DB->query($queryCount); 
    $num = mysql_num_rows ($query); //count num rows 
    $per_page=5; //default 5 results per page 
$start=$per_page*($page-1); //start for select on next page (page2, 3, 4,5) 
$end=min($num,$page*$per_page); //end 


//here is select for your results. Be careful for LIMIT in the select! 
$query = "SELECT * FROM page LIMIT $start, $per_page "; 


//page bottom, where you want to put your numbers 
$pages=ceil($num/$per_page); 
    for($s=1; $s<=$pages; $s++) 
    { 
    if($s==$page) 
     $numPage .= "[$s] "; 
    else 
     $numPage .= "<a href='index.php?page=$s'>$s</a> "; 
    } 

echo $numPage; 

>

No he probado, pero creo que debe trabajar :-)

respecto cind, Ivan

?
+0

El código funciona pero esto simplemente imprime todos los números de página. La cuestión es limitar los números de página a, por ejemplo, 10 números de página solamente. si el usuario está en la página 12, debe mostrar, por ejemplo, 10 a 20, etc. –

Cuestiones relacionadas