Foreach - Pagination with images

Asked

Viewed 471 times

1

I’m trying to display images instead of numbers in the pagination.

I need help getting inside the for these images that are coming from the variable $aImages in the foreach,

       $maximo = 1;
        $pagina = isset($_GET['pagina']) ? ($_GET['pagina']) : '1'; 
        $pagina2 = $pagina + 1;
        $inicio = $pagina - 1;
        $inicio = $maximo * $inicio; 

        //CONSULTA PARA CONTAR TODOS REGISTROS
        $strCount = "SELECT COUNT(*) AS 'total_images' FROM posts, images
    WHERE posts.id_posts = images.posts_ID
    AND slug='".$_GET['slug']."'";
            $varstrCount = $crud->verdados($strCount);
            $total = 0;
            if(count($varstrCount)){
                foreach ($varstrCount as $row) {
                        $total = $row["total_imagens"]; 
                }
            }

            //CONSULTA PARA LIMITAR OS REGISTROS NA PAGINAÇÃO
            $resultado =  "SELECT * FROM posts, images
                         WHERE posts.id_post = images.posts_ID
                         AND slug='".$_GET['slug']."' ORDER BY id_posts LIMIT $inicio,$maximo";

            //EXECUTA A CONSULTA            
            $varresultado = $crud->verdados($resultado);

            $max_links = 10;
            $previous = $pagina - 1; 
            $next = $pagina + 1; 
            $pgs = ceil($total / $maximo);  

         //CONSULTA PARA AGRUPAR IMAGENS RELACIONADAS AO ID

          $stmt = $DB_con->prepare("SELECT 
                                  posts.*,
                                  COUNT(0) total, 
                                  GROUP_CONCAT(dir_image SEPARATOR '|') images
                                  FROM 
                                    posts
                                 INNER JOIN images ON (posts.id_post = images.post_id )
                                 WHERE
                                   slug=:slug
                                 GROUP BY
                                 id_post
                                  ");
         //EXECUTA A CONSULTA
         $stmt->execute(array(":slug"=>$_GET['slug']));

         while($row=$stmt->fetch(PDO::FETCH_ASSOC))
         {
             $aImages = explode('|', $row['images']);



           for($i=$pagina-$max_links; $i <= $pgs; $i++) {
               foreach ($aImages as $sImage) {
               echo "<a href='".BASE_URL.$slug."-".($i)."'><img src='".BASE_URL.$sImage."' ></a>";  ;                                       

               }

            }

}

The idea is to have that final result:

inserir a descrição da imagem aqui

These are the tables in DB:

Table IMAGES looks like this:

id_images | dir_image | post_id
1           image1.jpg  1
2           image2.jpg  1
3           image3.jpg  1
4           image4.jpg  1
5           image5.jpg  2
6           image6.jpg  2
7           image7.jpg  2
8           image8.jpg  2

Table POSTS:

id_post | slug          | title
1         title_post      Title Post 
2         title_post_2    Title Post 2

As an example the variable $aImages has 5 images coming from DB, the order prints correctly but each image prints repeatedly 15 times did not understand the reason, need each print only once.

I appreciate help

  • for() from the inside is printing the image of for each from the outside several times. Do you need it? If you need it, you need to rethink your paging. I think it is not the case to use foreach if it is to paginate. And another thing, $maximo has to catch the size of $aImages.

  • Thanks @Bacco o for is responsible for adding the pagination number $i, I don’t know how to do it without it

1 answer

2

Note: This reply was posted to a previous edition of the question.

Follow a simple and didactic example of paging, to serve as an example:

$imagens = '/1.jpg|/2.jpg|/3.jpg|/4.jpg|/5.jpg|/6.jpg|/7.jpg|/8.jpg';
$aImages = explode( '|',  $imagens );

$porPagina = 3;
$total = count( $aImages );
$paginas = ceil( $total / $porPagina ); 

for( $pagina = 0; $pagina < $paginas; ++$pagina ) {
   echo 'Pagina ' . ( $pagina + 1 ) . '<br>' . PHP_EOL;

   $offset = $pagina * $porPagina;
   for( $item = $offset ; $item < $total && $item < $offset + $porPagina; ++$item ) {
       echo '<img src="'.BASE_URL.$aImages[$item].'" ></a>' . PHP_EOL;
   }
}

See working on IDEONE.

Of course, in this case, you will have to adapt to the actual situation of your code. If you show only one page at a time, just delete the for( $pagina outside, and define the variable externally.

  • Thank you @Bacco your code is clean objective and functional, but in my case I take advantage of some variables in other parts of the project. I updated the question so you have a better sense of what I’m doing

  • Basically I made some names to illustrate what is each thing. I think you just have to replace things with the right names, which will work. The simple fact that you take the loop out, and catch the $page from Slug already does what you want. The outside loop was just for you to see the working inside (and see how I calculated the offset to determine the items on the current page)

  • PS: If it’s not a real "Paging" and you want to show all the images, just do what I said in the comments: put the foreach inside the is.

  • With the foreach inside the for appears 1 image at a time in the right order but repeating several times the sequence of 5 images

  • With the for inside the foreach appears each image 15 times but right sequence tbm

  • You cannot mix while with for. You can use while to mount an array, and use that array in for (but not while). And inside the is that will use the explode (otherwise the array will always be the same).

  • è que dentro do while tem outros parte html e php que estou imprimindo conforme a consuldo do DB como titulo, Slug, conteudo, etc. Paginação de imagens está dentro do conteudo, so se tiro o while igura todo o restante e mesmo a propria paginação

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.