I know the question already has a chosen answer, but I will still respond and make some comments.
1st
Why is the table structure like this ? Since there are several users / names for different uses, why are they all on the same line?
See an example of the reshaped 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 SQL
code in the database in use.
2
Do I really need to run looping
twice ? See, in the example you posted above, you have a looping for
within a while
. I mean, here I do not see any need to do this, or maybe you have been forced to do this because of estrutura
of your table.
I would do something like this:
$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 that I have a single looping
, which does exactly the same thing as your code did, as well as being a good practice is simple.
Or, this way:
...
print "<div id=\"nomes\">";
while($linha = $sql->fetch_array()){
print $linha["nome"] . "<br/>";
}
print "</div>";
...
That would make the returned names stay in a single <div>
tag.
Another thing is, if the goal is to limit the number of results to be processed and subsequently displayed, why not use the LIMIT
clause?
See another example:
$sql = $conexao->query("SELECT * FROM materias LIMIT 4");
This means that of the 9 names in the table, only the first 4 are selected, and then printed in the loop.
I hope you understood. Good luck.