0
My scenario is this: I have a function called searchUsuario()
function buscaUsuario($conexao)
{
$retornar = array();
$query = mysqli_query($conexao, "SELECT user_name FROM usuarios");
while($result = mysqli_fetch_assoc($query))
{
$retornar[] = $result;
}
return $retornar;
}
Where I also have a file called search-user.php and there is the following code snippet:
<?php
$all = buscaUsuario($conexao);
$ab = sizeof($all);
$i = 0;
for ($i = 0; $i < $ab; $i++)
{
?>
<tr>
<td><?=implode($all[$i])?></td>
</tr> <?php
}
?>
I am returning the query in an array to be displayed in a table. Previously I tried to do it in a more succinct way (at least for me) but I entered an infinite loop and crashed the browser. And this other way was the following: in the function searchUsuario() I created a variable that received mysqli_fetch_array() and returned this variable. Then, in search-user.php I called this function and played inside a while so that the table was populated until there were no more rows inside the array... And that (as I said up there) caused the browser to crash, so I decided to do it the way I showed them. However, if I add one more field in select and have it printed inside it, the cells of each row in the table are not populated, only the first line, so: userName
I wanted to understand what I’m doing wrong and what would be the best way to do what I’m trying to do... Thanks Folks!
A foreach does not solve?
$all = buscaUsuario($conexao); foreach($all as $item){ echo $item['user_name'] .'<br>';}
– rray
I had already tried, but it gives the following error: Warning: Illegal string offset 'user_name'
– Cesar Augusto
So the column name is wrong, that’s all. What’s the correct column name? When in doubt change the
echo $item ...
forprint_r($item)
inside the foreach.– rray
Nope, that’s right. user_name
– Cesar Augusto
Puts the result of
print_r()
in the comment that we have already solved haha– rray
The result is: "admin", of which is one of the registered user_name... I believe showed admin first by being ordered alphabetically
– Cesar Augusto
Not only does admin have more things, the return should be something like this
Array ( [chave] => valor )
– rray
Worse than not brother, returns only "admin" : There in the other file, change mysqli_fetch_assoc to mysqli_fetch_array and print_R returned two admin
– Cesar Augusto
Aah, inside the foreach, just leave
echo $item .'<br>';
– rray
Again appeared only "admin"
– Cesar Augusto
So now you’re right to just format in html table, or missed something?
– rray
Not really, as I have 5 user_name in my database and only one record is being displayed. It is also already formatted in html table D:
– Cesar Augusto