Problem with php page

1

I set up a very rudimentary pager, when entering my index.php page a query of all the records. To do this, I only pass the page number to show the url and reload the same page, which works.

Now I have the need to show and paginate the records by category. I put a select in my index.php and when I choose category I pass category + '1' to another page called categoria.php where I have the same functions as in my index (I copy how this value happened):

<select id="combo_categorias" name="cat" onchange="location.href='categoria.php?num=' + this.value +'1';">

I control by url the value of the category that is a string, eg: 'shoe shop' + a 1, since the first page to be displayed is always 1.

The issue is that already stopped in categoria.php , when I have paginada more than 1 page does not work, I can pass the value of the page .. but the value of the category is lost and I can not find the way to solve it. Copy the code:

   <?php  
        $variable=" ";
        $rest=" ";
        $restvar=" ";

        //Si lo recibido por GET
        if (isset($_GET['num'])) {
            $variable=$_GET['num'];
        }

        //Saco del GET el último dígito
            $rest=substr($variable, -1);

        //Saco todo menos el último dígito
            $restvar=substr($variable, 0, -1);

        //Convierto lo sustraído en la variable
            $variable=$restvar;
//            $_SESSION["cat_elegida"]=$variable;
    ?>

    <div class="pagina">
        <?php include ("cabecera.php"); ?>
            <div class="contenedor">
                    <div class="productos">
        <?php

        $consulta="select * from productos where categoria LIKE '$variable' ORDER BY id ASC";
        $result = mysqli_query($con, $consulta);
        $nro_reg = mysqli_num_rows($result);

        if ($nro_reg==0) {
            ?>    
                <div class="superado_stock">    
                <?php
                    echo "<h4> </h4>";
                    echo "<h4><strong>Producto temporalmente agotado</strong></h4>";
                    echo "<h4> </h4>";
                ?>
                </div>                               
                <?php
            }

        $reg_por_pagina=12;

        if (isset($_GET['num'])) {
            $nro_pagina=$rest;
            var_dump($nro_pagina);
            var_dump($variable);
        } else {
            $nro_pagina=1;
        }

        if (is_numeric($nro_pagina))
            $inicio=(($nro_pagina-1)*$reg_por_pagina);
        else
            $inicio=0;

        $consulta=mysqli_query($con,"select * from productos where categoria LIKE '$variable' order by id ASC limit $inicio, $reg_por_pagina");
        $canti_paginas=ceil($nro_reg/$reg_por_pagina);
        ?>
        <?php
            while ($filas=mysqli_fetch_array($consulta, MYSQLI_ASSOC)) {
            echo mysql_error();
                $id=$filas['id'];
                $imagen=$filas['imagen'];
                $nombre=$filas['nombre'];
                $descripcion=$filas['descripcion'];
                $precio=$filas['precio'];
                $stock=$filas['stock'];
                $fecha=$filas['fecha'];
                if($imagen=="No disponible"){
                    $imagen="IMAGENES/ImagenNoDisponible100.gif";
                }                
        ?>

            <div class="caja">
                <div class="caja_imagen"><img src="<?php echo $imagen?>" style=widht="100" height="100"/>
                        <p class="caja_nombre"><?php echo $nombre?></p>
                        <p class="caja_precio">$ <?php echo $precio?></p>
                </div>   
                <div class="caja_boton">
                    <form action="detalle.php" method="post" name="detalle">
                        <input name="id" type="hidden" value="<?php echo $id ?>" />
                        <input class="boton_detalle2" type="submit" value="Detalle">
                    </form>
                </div>
            </div>
       <?php
            }
        ?>
            </div>
        </div>       
    <!-------------------------------------------------------------------------------------------->
    <!-----------------------------PAGINADOR------------------------------------------------------>
    <!-------------------------------------------------------------------------------------------->      

            <div id="paginador" align="center">
                        <?php
                        if ($nro_pagina>1)
                            echo "<a href='categoria.php?num=".($nro_pagina-1) ."' >Anterior</a> ";

                        for ($i=1;$i<=$canti_paginas;$i++){

                            if ($i==$nro_pagina)
                                echo "<span>$i </span>" ;
                            else
                                echo "<a href='categoria.php?num=$i'>$i</a> ";
                        }

                        if ($nro_pagina<$canti_paginas)
                            echo "<a href='categoria.php?num=". ($nro_pagina+1) ."' >Siguiente</a> ";
                        ?>
            </div>
    <!-------------------------------------------------------------------------------------------->
    <!--------------------------FIN DEL PAGINADOR------------------------------------------------->
    <!-------------------------------------------------------------------------------------------->   
        </div>   
    </div>

Maybe I could pass 2 values x url, but I do not succeed.

    
asked by look68 04.11.2016 в 15:05
source

2 answers

2

You do not need sessions, just pass the two variables to the script, for example like this:

<select id="combo_categorias" name="cat" onchange="location.href='categoria.php?cat=' + this.value + '&num=1';">

And already in your script category.php, something like this (I've done the editing here, so maybe the code has errors, but it gives you the idea of where I want to go:

<?php  
    $categoria = isset($_GET['cat'])?$_GET['cat']:"%";
    $categoria = mysqli_real_escape_string($categoria);
    $num = isset($_GET['num'])?$_GET['num']:"1";
    if (!is_numeric($num)) {
        $num = "1";
    }
?>
   
<div class="pagina">
    <?php include ("cabecera.php"); ?>
    <div class="contenedor">
        <div class="productos">
    <?php
        $consulta="select * from productos where categoria LIKE '$categoria' ORDER BY id ASC";
        $result = mysqli_query($con, $consulta);
        $nro_reg = mysqli_num_rows($result);
        
        if ($nro_reg==0) {
    ?>    
                <div class="superado_stock">    
                    <h4> </h4>
                    <h4><strong>Producto temporalmente agotado</strong></h4>
                    <h4> </h4>
                </div>                               
    <?php
        }
                        
        $reg_por_pagina=12;
        
        $inicio=(($num - 1) * $reg_por_pagina);
        
        $consulta=mysqli_query($con,"select * from productos where categoria LIKE '$categoria' order by id ASC limit $inicio, $reg_por_pagina");
        $canti_paginas=ceil($nro_reg/$reg_por_pagina);
        while ($filas=mysqli_fetch_array($consulta, MYSQLI_ASSOC)) {
            echo mysql_error();
            $id=$filas['id'];
            $imagen=$filas['imagen'];
            $nombre=$filas['nombre'];
            $descripcion=$filas['descripcion'];
            $precio=$filas['precio'];
            $stock=$filas['stock'];
            $fecha=$filas['fecha'];
            if($imagen=="No disponible"){
                $imagen="IMAGENES/ImagenNoDisponible100.gif";
            }                
    ?>
        
            <div class="caja">
                <div class="caja_imagen"><img src="<?php echo $imagen?>" style=widht="100" height="100"/>
                        <p class="caja_nombre"><?php echo $nombre?></p>
                        <p class="caja_precio">$ <?php echo $precio?></p>
                </div>   
                <div class="caja_boton">
                    <form action="detalle.php" method="post" name="detalle">
                        <input name="id" type="hidden" value="<?php echo $id ?>" />
                        <input class="boton_detalle2" type="submit" value="Detalle">
                    </form>
                </div>
            </div>
    <?php
        }
    ?>
            </div>
        </div>       
    <!-------------------------------------------------------------------------------------------->
    <!-----------------------------PAGINADOR------------------------------------------------------>
    <!-------------------------------------------------------------------------------------------->      

            <div id="paginador" align="center">
    <?php
        if ($num>1)
          echo "<a href='categoria.php?cat=$categoria&num=".($num-1) ."'>Anterior</a>";

        for ($i=1;$i<=$canti_paginas;$i++){

            if ($i==$nro_pagina)
                echo "<span>$i </span>" ;
            else
                echo "<a href='categoria.php?cat=$categoria&num=$i'>$i</a>";
        }
                
        if ($num<$canti_paginas)
            echo "<a href='categoria.php?cat=&categoria&num=". ($nro_pagina+1) ."' >Siguiente</a>";
    ?>
            </div>
    <!-------------------------------------------------------------------------------------------->
    <!--------------------------FIN DEL PAGINADOR------------------------------------------------->
    <!-------------------------------------------------------------------------------------------->   
        </div>   
    </div>
    
answered by 04.11.2016 в 16:09
0

/////////////////////////////////////////////// ////////////////////////// from the controller:

        //Limito la busqueda 
        $pagination = 1; 
        //examino la página a mostrar y el inicio del registro a mostrar 
        $page = 1;
        $start = 0;

        if(isset($_GET["page"])){
            $page = $_GET["page"];
            $start = ($page - 1) * $pagination;
        }

        //veo el número total de campos que hay en la tabla con esa búsqueda 
        $total_rows = $this->db->get('datos_estudiante');
        //echo count($total_rows);

        //calculo el total de páginas 
        $total_pages = ceil($total_rows / $pagination); 
        /*//pongo el número de registros total, el tamaño de página y la página que se muestra 
        echo "Número de registros encontrados: " . $total_rows . "<br>"; 
        echo "Se muestran páginas de " . $pagination . " registros cada una<br>"; 
        echo "Mostrando la página " . $page . " de " . $total_pages . "<p>";*/

        //muestro los distintos índices de las páginas, si es que hay varias páginas 
        if ($total_pages > 1){ 
            for ($i = 1;$i <= $total_pages; $i++){ 
               if ($page.'?' == $i){
                  //si muestro el índice de la página actual, no coloco enlace 
                  $current .= '<li class="active"><a>'.$page.'</a></li> '; 
                } else {
                  //si el índice no corresponde con la página mostrada actualmente, coloco el enlace para ir a esa página 
                  $next .= '<li><a href="'.base_url('').'datos_estudiante/index/?page='.$i.'">'.$i.'</a></li> '; 
                }
            } 
        }
        //$this->input->server('HTTP_USER_AGENT');

        $data['titulo'] = 'Bienvenido';
        $data['query'] = $this->Model_Datos_Estudiante->all_paginate($start, $pagination);
        $data['contenido'] = 'datos_estudiante/index';
        $data['paginate'] = $current.$next;
        $data['data'] = $data;
        $this->load->view('template/template',$data);

/////////////////////////////////////////////// ////////////////////////// From the model:

public function all_paginate($start, $pagination){
    $query = $this->db->query('SELECT * FROM datos_estudiante LIMIT '.$start.','.$pagination);
    return $query;
}

/////////////////////////////////////////////// ////////////////////////// From the view:

<?php foreach($query as $registro): ?>
   ACA VAN LOS DATOS
<?php endforeach; ?>
answered by 31.07.2017 в 08:25