Foros del Web » Programando para Internet » PHP »

[SOLUCIONADO] Paginación con PHP: Encuentra resultados pero no pagina

Estas en el tema de Paginación con PHP: Encuentra resultados pero no pagina en el foro de PHP en Foros del Web. Chicos me sucede una cosa muy curiosa. El caso es que ya he comprobado con echos todas las salidas de las variables para ver en ...
  #1 (permalink)  
Antiguo 12/06/2013, 14:01
 
Fecha de Ingreso: mayo-2013
Ubicación: Valladolid
Mensajes: 8
Antigüedad: 10 años, 11 meses
Puntos: 0
Pregunta Paginación con PHP: Encuentra resultados pero no pagina

Chicos me sucede una cosa muy curiosa. El caso es que ya he comprobado con echos todas las salidas de las variables para ver en qué momento me falla pero no logro encontrar el fallo y ya se sabe que 4 ojos (o más) ven más que dos.

El tipo de paginación es sencilla:
- Quiero que muestre 10 registros en cada fila --> Esto funciona
- Que diga el número de registros que ha encontrado en la consulta --> Esto funciona
- Que saque tantas páginas como sean necesarias para mostrar todos los resultados --> No funciona

Me falla porque o me saca sólo 10 registros y cuando doy a siguiente me dice que no encuentra resultados; o me saca todo el tocho de registros en una sola página.

El código es el siguiente:

Código PHP:
<?php

// EVITAMOS PROBLEMAS DE ESCRITURA: ACENTOS Y EÑES
    
header('Content-Type: text/html; charset=ISO-8859-1');

// EVITAMOS MOSTRAR ERRORES
    
error_reporting(E_ALL & ~E_NOTICE);

// COMPROBAMOS QUE VIENE DEL BUSCADOR SINO REDIRECCIONAMOS CON UN ELSE
    
if((isset($_POST['comautonoma'])and !empty ($_POST['comautonoma'])) or (isset($_POST['provincia'])and !empty($_POST['provincia'])) or (isset($_POST['preciocat']) and !empty($_POST['preciocat'])) or (isset($_POST['codigopostal']) and !empty($_POST['codigopostal']))) {    
    echo <<< html
        <html>
        <head>
            <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
            <meta name="Microsoft Theme" content="none, default">
            <meta name="Microsoft Border" content="none, default">

            <title>Resultados</title>
            <link href="meneame.css" type="text/css" rel="stylesheet">
    
        </head>

<!-- CUERPO DE LA WEB -->
        <body>
<!-- CONTAINER -->
        <div style="z-index: 1; top: 0px; left: 11px; width: 831px; background-position: center; margin: 0 auto 0 auto; height: 100%;" id="container" class="style41">
                
html;

// DATOS DE MYSQL
    
$servidor="mi servidor";
    
$user="user";
    
$pass="pass";
    
$bd="casas";
    
$conexion=mysql_connect($servidor,$user,$pass) or die (mysql_error("La base de datos no está disponible"));

// CONECTAMOS CON LA BASE DE DATOS    
    
mysql_select_db($bd,$conexion);

// COMPROBAMOS LOS DATOS REQUERIDOS POR EL USUARIO PARA REALIZAR LA CONSULTA
    
$comunidad=$_POST['comautonoma'];
    
$provincia=$_POST['provincia'];
    
$preciocat=$_POST['preciocat'];
    
$codigopost=$_POST['codigopostal'];

// ESTABLECEMOS EL NÚMERO DE FILAS POR PÁGINA Y LA FILA INICIAL
    
$filaspag 10;
    
$comienzo $_REQUEST['comienzo'];
    if (!isset(
$comienzo))
    {
        
$comienzo =0;
    }

    if(isset(
$comunidad) && $comunidad!="")
        {
        
$where .= "AND comunidadautonoma='$comunidad'";
        }
    if(isset(
$provincia) && $provincia !="")
        {
        
$where .=" AND provincia='$provincia'";
        }
    if(isset(
$preciocat) && $preciocat !="")
        {
        
$where .= " AND preciocat='$preciocat'";
        }
    if(isset(
$codigopost) && $codigopost !="")
        {
        
// SI HAN INTRODUCIDO UN CODIGO POSTAL REALIZAR LA CONSULTA SINO ELSE
            
$numero "$codigopost";
            
$codigopostal=$numero[0];
            
$codigopostal .=$numero[1];
            
$codigopostal .=$numero[2];
            
$codigopostal .=$numero[3];
            
$codigopostal .=$numero[4];
    
            
$where .= " AND codigopostal like '$codigopostal%'";

            
$where .="ORDER BY codigopostal";
            
$consulta "SELECT * FROM casas WHERE numplazas not like '0' $where";
        }
    else 
        {
            
$where .=" ORDER BY codigopostal ASC";
            
$consulta "SELECT * FROM casas WHERE numplazas not like '0' $where";
        }

// LLAMAMOS A LOS RESULTADOS Y COMPROBAMOS EL NÚMERO DE REGISTROS OBTENIDOS
    
$resultado=mysql_query($consulta) or die (mysql_error());
    
$numregistros=mysql_num_rows($resultado);

        
// SI EXISTEN REGISTROS ENTONCES MOSTRAMOS RESULTADOS SINO DAMOS ERROR
    
if ($numregistros>0)
        {                                
    
    echo <<< html
    
<!-- CUERPO CONTENIDO -->
    <div style="left: 12px; top: 252px; width: 831px; height: 550px; z-index: 1; background-color: #FCD68B; background-position: center; margin: 0 auto 0 auto; position: static;" id="cuerpocontenido" onclick="FP_goToURL(/*href*/'default.html')">
        <div style="position: static; width: 576px; height: 24px; z-index: 9; left: 63px; top: 461px; float: left; margin-left: 100px; visibility: visible; margin-top: -20px;" id="capa12" class="style24">
            Resultado consulta 
        </div>
    <br />
            
<!--TABLA DE DATOS-->            
    <table style="width: 800px; height: 250px">
        <td style="width: 13px">
        </td>
        <td style="width: 205px">
            <fieldset  style="border:2px solid #578fc4; width:100px; height:100%" class="round">
                <legend align="left"><b>Recomendadas</b>
                </legend>
                <marquee height="400"  direction="up" onmouseover="this.stop();" onmouseout="this.start();" scrolldelay="220" STYLE="background-color:transparent">
            <br />

        
html;
     
echo <<< html
                     <br />
                </marquee>
            </fieldset>
        </td>
        <td style="width: 11px">
        </td>
        <td class="style39" style="width: 1546px; height: 145px;">

        
<!--MOSTRAMOS PÁGINAS CON EL NÚMERO DE RESULTADOS ENCONTRADOS-->
html;

      
// Calculamos el número total de filas de la tabla
    
      
if ($numregistros 0)
        {
          
// Mostrar números inicial y final de las filas a mostrar
          
print ("<strong>Mostrando resultados " . ($comienzo 1) . " a ");
          
          if ((
$comienzo $filaspag) < $numregistros)
              {
                  print (
$comienzo $filaspag);
              }
        
          else
              {
                  print (
$numregistros);
                  
              }
              print (
" de un total de $numregistros </font></strong> <br>");
                }
            
          
// Mostramos botones anterior y siguiente
          
$estapagina $_SERVER['PHP_SELF'];
          
          if (
$numregistros $filaspag)
              {
                  echo 
"<right>";
                  if (
$comienzo 0)
                      {
                          print (
"  <A HREF='$estapagina?comienzo=" . ($comienzo $filaspag) . "'>Anterior</A> || ");
                      }                 
                  else
                      {
                          
//print (" Anterior || ");
                      
}
                  if (
$numregistros > ($comienzo $filaspag))
                      {
                      print (
"<A HREF='$estapagina?comienzo=" . ($comienzo $filaspag) . "'> Siguiente</A> \n");
                      }
                  else
                      {
                          
//print (" Siguiente \n");
                      
}
              }
              print (
"\n ");
              echo 
"</right>";
          
              
echo <<< html
            
<!--TABLA DE RESULTADOS-->
                                                                                                                    
html;

// MIENTRAS HAYA REGISTROS OBTENIDOS DE LA CONSULTA MOSTRAR
        
    
$instruccion "$consulta limit $comienzo, $filaspag";
    
$consulta mysql_query ($instruccion$conexion)        or die ("Fallo en la consulta");

// Mostrar resultados de la consulta
    
$numregistros mysql_num_rows ($consulta);
    if (
$numregistros 0)
    {
        
echo <<< html
        <table style="width: 100%" border="0">
        <td class="style39" style="width: 210px">
        <center><h3>Dirección Casa</h3></center>
        </td>
        <td class="style39" style="width: 50px">
        <h3><center>Plazas</center></h3>
        </td>
        <td  class="style39" style="width: 35px" >
        <h3><center>C.Postal</center></h3>
        </td>
html;
        
        while (
$row=mysql_fetch_assoc($consulta))
//            {


    //    for ($i=0; $i<$numregistros; $i++)
            
{
                
$id=$row['id_casa'];
                echo 
"<tr><td ><center><a target=\'_blank\' href='detallesres.php?id=$id'>$row[nombre]</a></center></td>";
                echo 
"<td ><center>$row[numplazas]</center></td>";
                echo 
"<td ><center>$row[codigopostal]</center></td></tr>";
            }
    
        
echo <<< html
         </table>
        </td>
    </table>

html;
    }    

echo <<< html
<!--CERRAMOS CUERPO CONTENIDO-->        
    </div>

        
<!-- EL PIE DE PÁGINA -->
            <br />
        <div style="left: 11px; top: 717px; width: 826px; height: 36px; z-index: 1; margin: 0 auto 0 auto; background-color: #CCCCCC; background-position: center" id="pie">
            <div style="position: static; left: 640px; top: 610px; width: 164px; height: 19px; z-index: 1; float: right; margin: 20px 20px 0 0" id="infopieizq" class="style3">
                <strong>
                <div style="margin: -5px 0 0 0; position: static; left: 694px; top: 1001px; width: 146px; height: 24px; z-index: 1; float: right" id="capa9" class="style20">
                <a href="acceso.html">Login</a>
                </div>
                </strong>
            </div>
            <div style="position: static; left: 100px; top: 610px; width: 164px; height: 19px; z-index: 1; float: left; margin: 10px 0 0 20px" id="infopieizq0" class="style33">
                <a href="mailto:[email protected]">mi e-mail</a> 
            </div>
            <div style="position: static; left: 100px; top: 610px; width: 164px; height: 19px; z-index: 1; float: left; margin: 10px 0 0 150px" id="infopieizq1" class="style38">
html;
                
//$row=mysql_fetch_array($resultados);
                
$sede=$row['telefonosede'];
                echo 
$sede;
                
echo <<< html
            </div>
        </div>

        
<!-- CIERRE DEL CONTAINER, BODY Y HTML -->
        </div>
    </body>
</html>


html;

// CERRAMOS LOS DOS IF: DE DATOS DE BUSCADOR Y EL DE RESULTADOS
// YA QUE NO VIENE DEL BUSCADOR O NO SE HAN ENCONTRADO RESULTADOS
        
}
    }
    else
        {
        echo 
header("Location:buscador.php?error=1");
        }
  #2 (permalink)  
Antiguo 12/06/2013, 14:12
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 17 años, 11 meses
Puntos: 2135
Respuesta: Paginación con PHP: Encuentra resultados pero no pagina

El error es sencillo, al estar filtrando por POST, no puedes paginar usando links <a> tienes que cambiar y hacerlo todo por GET, o usar backlinks y formularios ocultos para pasar las cosas por POST.

Saludos.
  #3 (permalink)  
Antiguo 12/06/2013, 16:19
 
Fecha de Ingreso: mayo-2013
Ubicación: Valladolid
Mensajes: 8
Antigüedad: 10 años, 11 meses
Puntos: 0
Respuesta: Paginación con PHP: Encuentra resultados pero no pagina

Dios!!! Pues seguro que tienes razón!!! me obcequé tanto con que podría ser algún condicional que puse que no caí en la cuenta de ese detalle!!!

Voy a probar a ver si ahora funciona y termino de confirmar tu respuesta a mi problema!!
  #4 (permalink)  
Antiguo 13/06/2013, 00:25
 
Fecha de Ingreso: mayo-2013
Ubicación: Valladolid
Mensajes: 8
Antigüedad: 10 años, 11 meses
Puntos: 0
Respuesta: Paginación con PHP: Encuentra resultados pero no pagina

Pues no puede ser eso Gator porque ya lo cambié y sigue sin funcionar, me filtra los 10 registros y cuando doy a página siguiente se queda la pantalla en blanco no sale ningún resultado más.

Además con el código que tenía ahí los enlaces de las residencias por url me funcionaban lo único que no funcionaba era la url del siguiente para mostrar más resultados y ahora no me funciona ni una cosa ni la otra...:S

Código PHP:
<?php 

// EVITAMOS PROBLEMAS DE ESCRITURA: ACENTOS Y EÑES 
    
header('Content-Type: text/html; charset=ISO-8859-1'); 

// EVITAMOS MOSTRAR ERRORES 
    
error_reporting(E_ALL & ~E_NOTICE); 

// COMPROBAMOS QUE VIENE DEL BUSCADOR SINO REDIRECCIONAMOS CON UN ELSE 
    
if((isset($_GET['comautonoma'])and !empty ($_GET['comautonoma'])) or (isset($_GET['provincia'])and !empty($_GET['provincia'])) or (isset($_GET['preciocat']) and !empty($_GET['preciocat'])) or (isset($_GET['codigopostal']) and !empty($_GET['codigopostal']))) {     
    echo <<< 
html 
        
<html
        <
head
            <
meta http-equiv="Content-Type" content="text/html; charset=utf-8"
            <
meta name="Microsoft Theme" content="none, default"
            <
meta name="Microsoft Border" content="none, default"

            <
title>Resultados</title
            <
link href="meneame.css" type="text/css" rel="stylesheet"
     
        </
head

<!-- 
CUERPO DE LA WEB --> 
       
<!-- 
CONTAINER --> 
                       
html

// DATOS DE MYSQL 
    
$servidor="mi servidor"
    
$user="user"
    
$pass="pass"
    
$bd="casas"
    
$conexion=mysql_connect($servidor,$user,$pass) or die (mysql_error("La base de datos no está disponible")); 

// CONECTAMOS CON LA BASE DE DATOS     
    
mysql_select_db($bd,$conexion); 

// COMPROBAMOS LOS DATOS REQUERIDOS POR EL USUARIO PARA REALIZAR LA CONSULTA 
    
$comunidad=$_GET['comautonoma']; 
    
$provincia=$_GET['provincia']; 
    
$preciocat=$_GET['preciocat']; 
    
$codigopost=$_GET['codigopostal']; 

// ESTABLECEMOS EL NÚMERO DE FILAS POR PÁGINA Y LA FILA INICIAL 
    
$filaspag 10
    
$comienzo $_REQUEST['comienzo']; 
    if (!isset(
$comienzo)) 
    { 
        
$comienzo =0
    } 

    if(isset(
$comunidad) && $comunidad!=""
        { 
        
$where .= "AND comunidadautonoma='$comunidad'"
        } 
    if(isset(
$provincia) && $provincia !=""
        { 
        
$where .=" AND provincia='$provincia'"
        } 
    if(isset(
$preciocat) && $preciocat !=""
        { 
        
$where .= " AND preciocat='$preciocat'"
        } 
    if(isset(
$codigopost) && $codigopost !=""
        { 
        
// SI HAN INTRODUCIDO UN CODIGO POSTAL REALIZAR LA CONSULTA SINO ELSE 
            
$numero "$codigopost"
            
$codigopostal=$numero[0]; 
            
$codigopostal .=$numero[1]; 
            
$codigopostal .=$numero[2]; 
            
$codigopostal .=$numero[3]; 
            
$codigopostal .=$numero[4]; 
     
            
$where .= " AND codigopostal like '$codigopostal%'"

            
$where .="ORDER BY codigopostal"
            
$consulta "SELECT * FROM casas WHERE numplazas not like '0' $where"
        } 
    else  
        { 
            
$where .=" ORDER BY codigopostal ASC"
            
$consulta "SELECT * FROM casas WHERE numplazas not like '0' $where"
        } 

// LLAMAMOS A LOS RESULTADOS Y COMPROBAMOS EL NÚMERO DE REGISTROS OBTENIDOS 
    
$resultado=mysql_query($consulta) or die (mysql_error()); 
    
$numregistros=mysql_num_rows($resultado); 

         
// SI EXISTEN REGISTROS ENTONCES MOSTRAMOS RESULTADOS SINO DAMOS ERROR 
    
if ($numregistros>0
        {                                 
     
    echo <<< 
html 
     
<!-- CUERPO CONTENIDO --> 
                 
<!--
TABLA DE DATOS-->             
    <
table style="width: 800px; height: 250px"
        <
td style="width: 13px"
        </
td
        <
td style="width: 205px"
            <
fieldset  style="border:2px solid #578fc4; width:100px; height:100%" class="round"
                <
legend align="left"><b>Recomendadas</b
                </
legend
                <
marquee height="400"  direction="up" onmouseover="this.stop();" onmouseout="this.start();" scrolldelay="220" STYLE="background-color:transparent"
            <
br /> 

         
html
      
echo <<< 
html 
                     
<br /> 
                </
marquee
            </
fieldset
        </
td
        <
td style="width: 11px"
        </
td
        <
td class="style39" style="width: 1546px; height: 145px;"

         
<!--
MOSTRAMOS PÁGINAS CON EL NÚMERO DE RESULTADOS ENCONTRADOS--> 
html

       
// Calculamos el número total de filas de la tabla 
     
      
if ($numregistros 0
        { 
          
// Mostrar números inicial y final de las filas a mostrar 
          
print ("<strong>Mostrando resultados " . ($comienzo 1) . " a "); 
           
          if ((
$comienzo $filaspag) < $numregistros
              { 
                  print (
$comienzo $filaspag); 
              } 
         
          else 
              { 
                  print (
$numregistros); 
                   
              } 
              print (
" de un total de $numregistros </font></strong> <br>"); 
                } 
             
          
// Mostramos botones anterior y siguiente 
          
$estapagina $_SERVER['PHP_SELF']; 
           
          if (
$numregistros $filaspag
              { 
                  echo 
"<right>"
                  if (
$comienzo 0
                      { 
                          print (
"  <A HREF='$estapagina?comienzo=" . ($comienzo $filaspag) . "'>Anterior</A> || "); 
                      }                  
                  else 
                      { 
                          
//print (" Anterior || "); 
                      

                  if (
$numregistros > ($comienzo $filaspag)) 
                      { 
                      print (
"<A HREF='$estapagina?comienzo=" . ($comienzo $filaspag) . "'> Siguiente</A> \n"); 
                      } 
                  else 
                      { 
                          
//print (" Siguiente \n"); 
                      

              } 
              print (
"\n "); 
              echo 
"</right>"
           
               
echo <<< 
html 
             
<!--TABLA DE RESULTADOS--> 
                                                                                                                     
html

// MIENTRAS HAYA REGISTROS OBTENIDOS DE LA CONSULTA MOSTRAR 
         
    
$instruccion "$consulta limit $comienzo, $filaspag"
    
$consulta mysql_query ($instruccion$conexion)        or die ("Fallo en la consulta"); 

// Mostrar resultados de la consulta 
    
$numregistros mysql_num_rows ($consulta); 
    if (
$numregistros 0
    { 
         
echo <<< 
html 
        
<table style="width: 100%" border="0"
        <
td class="style39" style="width: 210px"
        <
center><h3>Dirección Casa</h3></center
        </
td
        <
td class="style39" style="width: 50px"
        <
h3><center>Plazas</center></h3
        </
td
        <
td  class="style39" style="width: 35px" 
        <
h3><center>C.Postal</center></h3
        </
td
html
         
        while (
$row=mysql_fetch_assoc($consulta)) 
//            { 


    //    for ($i=0; $i<$numregistros; $i++) 
            

                
$id=$row['id_casa']; 
                echo 
"<tr><td ><center><a target=\'_blank\' href='detallesres.php?id=$id'>$row[nombre]</a></center></td>"
                echo 
"<td ><center>$row[numplazas]</center></td>"
                echo 
"<td ><center>$row[codigopostal]</center></td></tr>"
            } 
     
         
echo <<< 
html 
         
</table
        </
td
    </
table

html
    }     

echo <<< 
html 
<!--CERRAMOS CUERPO CONTENIDO-->         
    </
div

         
<!-- 
EL PIE DE PÁGINA --> 
            <
br /> 
        <
div style="left: 11px; top: 717px; width: 826px; height: 36px; z-index: 1; margin: 0 auto 0 auto; background-color: #CCCCCC; background-position: center" id="pie"
            <
div style="position: static; left: 640px; top: 610px; width: 164px; height: 19px; z-index: 1; float: right; margin: 20px 20px 0 0" id="infopieizq" class="style3"
                <
strong
                <
div style="margin: -5px 0 0 0; position: static; left: 694px; top: 1001px; width: 146px; height: 24px; z-index: 1; float: right" id="capa9" class="style20"
                <
a href="acceso.html">Login</a
                </
div
                </
strong
            </
div
            <
div style="position: static; left: 100px; top: 610px; width: 164px; height: 19px; z-index: 1; float: left; margin: 10px 0 0 20px" id="infopieizq0" class="style33"
                <
a href="mailto:[email protected]">mi e-mail</a>  
            </
div
            <
div style="position: static; left: 100px; top: 610px; width: 164px; height: 19px; z-index: 1; float: left; margin: 10px 0 0 150px" id="infopieizq1" class="style38"
html
                
//$row=mysql_fetch_array($resultados); 
                
$sede=$row['telefonosede']; 
                echo 
$sede
                 
echo <<< 
html 
            
</div
        </
div

         
<!-- 
CIERRE DEL CONTAINERBODY Y HTML --> 
        </
div
    </
body
</
html


html

// CERRAMOS LOS DOS IF: DE DATOS DE BUSCADOR Y EL DE RESULTADOS 
// YA QUE NO VIENE DEL BUSCADOR O NO SE HAN ENCONTRADO RESULTADOS 
        

    } 
    else 
        { 
        echo 
header("Location:buscador.php?error=1"); 
        }

Última edición por Anisakys; 13/06/2013 a las 02:14 Razón: Introducción del código php actual con los cambios realizados
  #5 (permalink)  
Antiguo 13/06/2013, 02:40
 
Fecha de Ingreso: mayo-2013
Ubicación: Valladolid
Mensajes: 8
Antigüedad: 10 años, 11 meses
Puntos: 0
Respuesta: Paginación con PHP: Encuentra resultados pero no pagina

Vale ya está solucionado era una tontería... arriba cuando hago la comprobación de los datos con los isset tengo que añadir tambien isset ($_GET['comienzo'] sino cuando hace la comprobación como no recoge ninguno de las variables definidas no muestra la página y aparece en blanco.

Muchas gracias Gator diste con mi principal problema ^^

Etiquetas: mysql-php, paginador
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 07:20.