How to repeat columns up to "x" of times

Asked

Viewed 1,474 times

6

Well I have a column in my database with names, I write it on the screen, through this code:

<html>
    <head>
        <title>Pagina Inicial</title>
        <meta charset="utf8">
        <link rel="stylesheet" type="text/css" href="style.css">
    </head>
    <body>
<?php
;   include("connect.php");
    $consulta = "SELECT * FROM materias";
    $con = $mysqli->query($consulta) or die($mysqli->error);

    ?>
    <?php while($dado = $con->fetch_array()){
        ?>
<?php for($nomes =1; $nomes <= 9; $nomes++){?>
<div id="nomes">
        <?php echo $dado["$nomes"];?>
    </div>
    <?php } ?>      
        </div>
        <?php } ?>
    </body>
</html>

Este é as colunas da tabela

E ele escreve isto na tela

  • I would like to get this result: http://i.imgur.com/2PNBs4s.jpg

3 answers

5


A tip: organize your code, opening and closing the PHP tag several times can end up making you lose yourself. A hint is also to store HTML in a variable, and give echo at the end, or several echo during the run.

About the problem, I believe that just add one more for going from 1 to 4, as I noticed in the image along with a tag <br> to break line.

<?php 
    for ($i = 1; $i <= 4; $i++) {

        for($nomes =1; $nomes <= 9; $nomes++){

            <div id="nomes">
                <?php echo $dado["$nomes"];
            </div>

        }
        <br>
   } 
?>  
  • 3

    Thanks for your edition, I had forgotten a word. It’s nice now.

  • Thank you very much, I didn’t know it was possible to put more than one for, and thanks for the organizing tip, I’ll do this :D

5

I know that the question has already been answered, but I will nevertheless reply and make a few observations.

first

Why the table structure is like this ? Since there are several users/names for different uses, because they are all in the same line ?

See an example, from the reformulated table:

CREATE TABLE IF NOT EXISTS materias (
id INT(11) NOT NULL AUTO_INCREMENT,
nome VARCHAR(20) NOT NULL,
INDEX(nome),
UNIQUE KEY(id),
PRIMARY KEY(id)
) DEFAULT CHARSET=latin1;

INSERT INTO `materias`(`id`, `nome`) VALUES (NULL, 'Bruno'), (NULL, 'Bruna'), (NULL, 'Gabriel'), (NULL, 'Gabriela'), (NULL, 'Felipe'), (NULL, 'Andre'), (NULL, 'Luiz'), (NULL, 'Gustavo'), (NULL, 'Otavio');

If possible delete the current table in use, and run this code SQL in the database in use.

2nd

It is really necessary to execute the looping twice ? See, in the example you posted above, you have a looping for within a while. I mean, here I don’t see any need to do that, or maybe you were forced to do it because of estrutura of your table.

I’d do something like that:

$sql = $mysqli->query("SELECT * FROM materias");
if($sql->num_rows > 0){
    while($linha = $sql->fetch_array()){
        print "<div id=\"nomes\">";    
        print $linha["nome"];    
        print "</div>";
    }
    mysqli_free_result($sql);    
} else {
    die("Sem resultados");    
}
mysqli_close($mysqli);

Notice I have a single looping, that does exactly the same thing that your code did, besides being a good practice is simple.

Or else, in this way:

...
print "<div id=\"nomes\">";    
while($linha = $sql->fetch_array()){
    print $linha["nome"] . "<br/>";      
}
print "</div>";
...

That would make the returned names a single tag <div>.

Another thing is, if the goal is to limit the number of results to be processed and later displayed, why not use the clause LIMIT ?

See another example:

$sql = $conexao->query("SELECT * FROM materias LIMIT 4");

This means that of the 9 existing names in the table, only the first 4 will be selected, and later printed in the looping.

I hope you understand. good luck.

  • I understood yes, thanks for the help, the goal is not to limit, but rather repeat the column name

  • 1

    Look at the modifications I made. Yes, I even thought that part of your goal was to limit the number of results, because in the answer below the first looping had for ($i = 1; $i <= 4; $i++), and then another looping would appear. Either way, you can do so, which is equally effective and recommended most of the time.

0

It is simple to do but has to have a table that calls t_vez containing only fields "name number", that has numbers from 1 to 200. Then, you can see by the sql below, that is made a query in the table t_vendas, which has a field named vendaquantidade, that could be how many tokens will be printed.

The search checks if you have vendasquantidades greater than or equal to number, example if you have in the field sales quantities the number three then you will repeat 3 rows why in the number field of the table time you have number one (smaller), two (smaller) and three (equal).

SELECT * FROM  T_VENDAS AS A, T_VEZ AS B WHERE A.VENDAQUANTIDADE >= B.NUMERO 
  AND A.VENDANUMERO = ' + INTTOSTR(RESULTADO) + ' AND A.VENDAIMPRIMIR = "SIM" 
  ORDER BY A.VENDAQUANTIDADE, A.PRODUTONUMERO
  • Please collaborate with the quality of the site, providing a better organized and punctuated response, without using CAPS LOCK throughout the text.

Browser other questions tagged

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