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 would like to get this result: http://i.imgur.com/2PNBs4s.jpg
– Bruno Ferreira