Foros del Web » Programando para Internet » PHP »

Paginación de registros con PHP y MySQL

Estas en el tema de Paginación de registros con PHP y MySQL en el foro de PHP en Foros del Web. Hola amigos, nuevamente yo por aquí con una duda: Estoy utilizando Dreamweaver 8 e intenté realizar la paginación de los registros de mi tabla 'invoices' ...
  #1 (permalink)  
Antiguo 02/12/2008, 19:19
Avatar de vennersteve  
Fecha de Ingreso: noviembre-2008
Ubicación: San Andrés - Isla
Mensajes: 26
Antigüedad: 15 años, 4 meses
Puntos: 0
Pregunta Paginación de registros con PHP y MySQL

Hola amigos, nuevamente yo por aquí con una duda:

Estoy utilizando Dreamweaver 8 e intenté realizar la paginación de los registros de mi tabla 'invoices' ('facturas', in spanish, please...).

Creé el juego de registros especificando que se mostraran todas las columnas y ordenando de manera ascendente (SELECT * FROM invoice ORDER BY invoice.IdInvoice).

Ya hice click en el boton de probar y SI, me muestra los registros existentes en la tabla en el CUADRO DE DIALOGO DE DREAMWEAVER, no en el explorador.

Hice los cuatro links para: Primera, Anterior, Siguiente y Ultima paginas e implemente los comportamientos de servidor para mostrarlos segun el caso de si es o no la primera o ultima pagina.

Ahora no se como rayos hacer para que me MUESTRE los registros de forma paginada, los links cambian como si hubiese varias paginas, es decir, como si quisiera funcionar, pero no me muestra la informacion que deseo mostrar...

Alguien tiene alguna sugerencia para este caso??

La verdad he buscado mucho sobre paginacion de registros en PHP y no he logrado adaptarlo a mi forma de ver el lenguaje...

Cualquier ayuda sera altamente apreciada!!
  #2 (permalink)  
Antiguo 02/12/2008, 19:28
Avatar de stone_neo  
Fecha de Ingreso: abril-2004
Ubicación: Peru
Mensajes: 438
Antigüedad: 20 años
Puntos: 15
Respuesta: Paginación de registros con PHP y MySQL

Seria mucho mejor si mostraras tu codigo de la paginación para ver que errores tienes, en todo caso busca en este mismo foro hay script para paginación.
__________________
Rubén Darío Huamaní Ucharima
Web : http://www.gorilla-soft.com
Usuario Linux #382 100 :-)
  #3 (permalink)  
Antiguo 02/12/2008, 21:05
Avatar de vennersteve  
Fecha de Ingreso: noviembre-2008
Ubicación: San Andrés - Isla
Mensajes: 26
Antigüedad: 15 años, 4 meses
Puntos: 0
Busqueda Respuesta: Paginación de registros con PHP y MySQL

Cita:
Iniciado por stone_neo Ver Mensaje
Seria mucho mejor si mostraras tu codigo de la paginación para ver que errores tienes, en todo caso busca en este mismo foro hay script para paginación.
paginacion.php

Código PHP:
<?php require_once('Connections/cesfa_invoice.php'); ?>
<?php
$currentPage 
$_SERVER["PHP_SELF"];

$maxRows_show_invoices 1;
$pageNum_show_invoices 0;
if (isset(
$_GET['pageNum_show_invoices'])) {
  
$pageNum_show_invoices $_GET['pageNum_show_invoices'];
}
$startRow_show_invoices $pageNum_show_invoices $maxRows_show_invoices;

mysql_select_db($database_cesfa_invoice$cesfa_invoice);
$query_show_invoices "SELECT * FROM invoice ORDER BY invoice.IdInvoice";
$query_limit_show_invoices sprintf("%s LIMIT %d, %d"$query_show_invoices$startRow_show_invoices$maxRows_show_invoices);
$show_invoices mysql_query($query_limit_show_invoices$cesfa_invoice) or die(mysql_error());
$row_show_invoices mysql_fetch_assoc($show_invoices);

if (isset(
$_GET['totalRows_show_invoices'])) {
  
$totalRows_show_invoices $_GET['totalRows_show_invoices'];
} else {
  
$all_show_invoices mysql_query($query_show_invoices);
  
$totalRows_show_invoices mysql_num_rows($all_show_invoices);
}
$totalPages_show_invoices ceil($totalRows_show_invoices/$maxRows_show_invoices)-1;

$queryString_show_invoices "";
if (!empty(
$_SERVER['QUERY_STRING'])) {
  
$params explode("&"$_SERVER['QUERY_STRING']);
  
$newParams = array();
  foreach (
$params as $param) {
    if (
stristr($param"pageNum_show_invoices") == false && 
        
stristr($param"totalRows_show_invoices") == false) {
      
array_push($newParams$param);
    }
  }
  if (
count($newParams) != 0) {
    
$queryString_show_invoices "&" htmlentities(implode("&"$newParams));
  }
}
$queryString_show_invoices sprintf("&totalRows_show_invoices=%d%s"$totalRows_show_invoices$queryString_show_invoices);
?>
<?php
    
include("constantes.php"); //Constantes para mostrar el texto
    
include ("calc_time1.php"); //Inicio de conteo de tiempo
?>
<html>
    <head>
        <title>C. E. S. F. A | <?php echo CHRDS?></title>
        <link rel="stylesheet" type="text/css" href="css/stylesheet.css">
        <link type="image/x-icon" href="favicon.ico" rel="shortcut icon">
    </head>
    <body bgcolor="#8f8f8f">
    <br><br>
        <table align="center" width="70%" bgcolor="#00CCFF" border="1" bordercolor="#000000">
            <tr>
                <td align="center">
                    <?php echo WEBSITETITLE?>
                </td>
            </tr>
            <tr>
              <td align="center">
              <h1><label><?php echo CHRDS?></label></h1><br>
              <?php if ($pageNum_show_invoices 0) { // Show if not first page ?>
                <a href="<?php printf("%s?pageNum_show_invoices=%d%s"$currentPage0$queryString_show_invoices); ?>">&laquo;</a>
                <?php // Show if not first page ?>
              <?php if ($pageNum_show_invoices 0) { // Show if not first page ?>
                <a href="<?php printf("%s?pageNum_show_invoices=%d%s"$currentPagemax(0$pageNum_show_invoices 1), $queryString_show_invoices); ?>">&lt;</a>
                <?php // Show if not first page ?>
              <?php if ($pageNum_show_invoices $totalPages_show_invoices) { // Show if not last page ?>
                <a href="<?php printf("%s?pageNum_show_invoices=%d%s"$currentPagemin($totalPages_show_invoices$pageNum_show_invoices 1), $queryString_show_invoices); ?>">&gt;</a>
                <?php // Show if not last page ?>
              <?php if ($pageNum_show_invoices $totalPages_show_invoices) { // Show if not last page ?>
                <a href="<?php printf("%s?pageNum_show_invoices=%d%s"$currentPage$totalPages_show_invoices$queryString_show_invoices); ?>">&raquo;</a>
                <?php // Show if not last page ?></td>
            </tr>
        </table>
        <?php echo WEBSITECREDIT?>
    </body>
</html>
<?php
mysql_free_result
($show_invoices);
?>
<?php
    
include ("calc_time2.php"); //Fin de conteo de tiempo
    
echo GENTIME$gen_timeReal .GEN_TIME //Mostrar tiempo empleado en generar página
?>
constantes.php

Código PHP:
<?php
define
('WEBSITETITLE','<label><font size=4 style=font-weight:bolder>C. E. S. F. A<br>
                Conversational English System For All</font><br>
                <font size=3>Ender A. Aguirre P. - NIT 98.501.254-0<br>
                20 de Julio Avenue. Hielo Nevado Sector 2<sup>nd</sup> floor - Tel: 5121335</font></label>'
);
define('WEBSITECREDIT','<div class=credit id=bottom><label>Software Developed by: Steve Venner | Serial Number: 0594081-5.2 | [email protected] | Tel: 3166234987</label>
        </div>'
);
define('PREVIEWFORMATTEXT','This is used to preview the blank invoice format which you should print if you run out of photocopied formats...');
define('PREVIEWFORMATLINK','Preview Blank Invoice Format');
define('GOTOLASTRECORDTEXT','This is used specially when you want to take a look at the last record entered into the invoice database...');
define('GOTOLASTRECORDLINK','Go to the last Record');
define('LOGOUTTEXT','This is used for logging out of the application, you must log in again if you want to either look at or create any record...');
define('LOGOUTLINK','Log Out');
define('WRONGPASSWORD','Incorrect password, please try again.');
define('ADMINISTRATORNAME','steve');
define('INVOICETEXT','Invoice');
define('LOGIN','Log In');
define('GB','Good Bye...');
define('UN','Username');
define('PW','Password');
define('FORMDATETEXT','Da<u>t</u>e');
define('DATETEXT','Date');
define('RECORDEDBYTEXT','Recorded by');
define('LOGGEDUSERTEXT','Logged User');
define('PHONETEXT','Phone Number');
define('FORMPHONETEXT','Phone <u>N</u>umber');
define('CUSTOMERTEXT','Customer');
define('FORMCUSTOMERTEXT','Custo<u>m</u>er');
define('ADDRESSTEXT','Address');
define('FORMADDRESSTEXT','Addre<u>s</u>s');
define('QTS','Qty');
define('QYL','Quantity');
define('FORMQYL','<u>Q</u>uantity');
define('DESCRIPT','Description');
define('FORMDESCRIPT','Descripti<u>o</u>n');
define('PRICE','Price');
define('TOTAL','Total');
define('SO','Start Over...');
define('SC','Save Changes...');
define('REFPAGCONT','Refresh this page contents');
define('CONF','Confirm ');
define('REG','Register');
define('BT','Back to the top');
define('ADM','Admin');
define('PAGEDINVOICESTEXT','This is used if you want to check the records out per page...');
define('PAGEDINVOICESLINK','View per Page');
define('REMFILL','Remember to fill in the invoice details before you click this button...');
define('SOB','Caution: This will reset the invoice fields to blank spaces...');
define('UR','User Registration');
define('SDH','Select Date Here...');
define('CHRDS','Review Invoices');
define('','');
define('GENTIME','<center><label>Page Generated in ');
define('GEN_TIME',' Seconds</center></label>');
?>
Tal vez haya más constantes de las que necesiten saber...

Última edición por vennersteve; 02/12/2008 a las 21:07 Razón: constantes.php es: ocassion_text.php en mi aplicacion...
  #4 (permalink)  
Antiguo 02/12/2008, 21:30
Avatar de vennersteve  
Fecha de Ingreso: noviembre-2008
Ubicación: San Andrés - Isla
Mensajes: 26
Antigüedad: 15 años, 4 meses
Puntos: 0
Respuesta: Paginación de registros con PHP y MySQL

Mirando en otros sitios, decidí copiar este código:

Código PHP:
<html>
<head>
<title>Páginación de resultados</title>
</head>
<body bgcolor=#FFFFFF> 
<?
// Datos de conexión a la base
$base="mi_base";
$con=mysql_connect(mi_host,mi_usuario,mi_clave);
mysql_select_db($base,$con);

if (!isset(
$pg))
$pg 0// $pg es la pagina actual
$cantidad=2// cantidad de resultados por página
$inicial $pg $cantidad;

$pegar "SELECT * FROM tabla ORDER BY Id LIMIT $inicial,$cantidad";
$cad mysql_db_query($base,$pegar) or die (mysql_error());

$contar "SELECT * FROM tabla ORDER BY Id"
$contarokmysql_db_query($base,$contar);
$total_records mysql_num_rows($contarok);
$pages intval($total_records $cantidad);
?>
<table align="center" cellpadding="1" cellspacing="1" border="1" width="80%">
    <tr>
        <td>
            <label>Invoice</label>
        </td>
        <td>
            <label>Date</label>
        </td>
        <td>
            <label>User</label>
        </td>
        <td>
            <label>Customer</label>
        </td>
        <td>
            <label>Address</label>
        </td>
        <td>
            <label>Phone</label>
        </td>
        <td>
            <label>Quantity</label>
        </td>
        <td>
            <label>Description</label>
        </td>
        <td>
            <label>Price</label>
        </td>
        <td>
            <label>Total</label>
        </td>
    </tr>
<?php
// Imprimiendo los resultados
while($array mysql_fetch_array($cad)) {
echo 
'<tr align=center><td>';
echo 
$array['Id']."</td><td>";
echo 
$array['DateInvoice']."</td><td>";
echo 
$array['LoggedUser']."</td><td>";
echo 
$array['CustomerInvoice']."</td><td>";
echo 
$array['AddressInvoice']."</td><td>";
echo 
$array['PhoneInvoice']."</td><td>";
echo 
$array['QuantityInvoice']."</td><td>";
echo 
$array['DescriptionInvoice']."</td><td>";
echo 
$array['PriceUnitInvoice']."</td><td>";
echo 
$array['PriceTotalInvoice']."</td></tr>";

?>
</table><br>

</body>
</html>
Este código funcionaba, creaba los link, pero misteriosamente los enumeraba: 1, 2, 4,... es decir, no mostraba el 3 y eso no me parece lo más indicado para usar en una aplicación, ahora mi pregunta es:

Como le hago para crear los links de Primera, Anterior, Siguiente y Ultima páginas, pero con botones y no con links de texto??
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 06:18.