Row and Column Loop in PHP

Asked

Viewed 483 times

-2

I’m trying to make a loop where every 5 records on the line, skips a line and so on until it reaches 6 lines, when it gets to 6 lines for the loop.

Example:

12345
12345
12345
12345
12345
12345
Para o laço

Thank you

  • 2

    And what is the code you are trying? Was there an error or was the result unexpected? If there was an error, what was it? If the result came out strange, what was different? Complete your question with this information that we can help you better.

  • I made a correction in the answer, see if it works for you using module concept.

1 answer

2


You can do using a condition with %module. It would be something like.

if($item%5==0){
   // insira o item + <br/> <-- onde br representa a quebra de linha
else 
   // insira o item normalmente

The logic is this: the percent operator % means module in programming, which checks the rest of the division of a certain value. In this case it is so, every time the value of the $item is divided by 5 and its rest is 0, then do something. As in the example, the tag is placed <BR/> to skip a line. See more details in the documentation.

Now see a complete code here using PDO. See:

<?php   

    // Instancia o objeto PDO
    $pdo = new PDO('mysql:host=localhost;dbname=db', 'root', '');
    // define para que o PDO lance exceções caso ocorra erros
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $consulta = $pdo->query("SELECT id FROM category;");

    $item = 1;
    while ($linha = $consulta->fetch(PDO::FETCH_ASSOC)) {
        // aqui eu mostro os valores de minha consulta

        if($item%5==0)
            echo "{$linha['id']}<br/>";
        else 
            echo "{$linha['id']}";
        }        
        $item++;
    }
?>
  • Hey, Ack Lay. What’s up? Sorry my lack of knowledge, but I did not understand the meaning of (%) in IF, if not to bother, you could explain the logic better. I want to learn. And thanks for the help friend.

  • Thank you Ack Lay.

  • I have another question with the query

  • If your question no longer has any related topic here in the community, feel free to open a new question.

  • Open question http://answall.com/questions/183976/query-para-campo-de-search. Thank you

Browser other questions tagged

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