Error while trying to list objects that are in the database when using Foreach();

Asked

Viewed 50 times

0

I am making this code to capture the elements of a table in my database but while executing the code foreach I get the bug and I don’t know what to do

Function to fetch data:

function listaUniformes($conexao) {
$uniformes = array();
$query = "select * from uniformes";
$resultado = mysqli_query($conexao, $query);
while($uniforme = mysqli_fetch_assoc($resultado)) {
    array_push($uniformes, $uniforme);
}
return $uniforme;

}

Foreach :

<?php
                listaUniformes($conexao);
                 foreach($uniformes as $uniforme) {
                    ?>
                     <tr>
                         <?= $uniforme['nome']; ?>
                     </tr>
            <?php } ?>

Error when I enter the page

Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\warehouse\uniformes.php on line 21
  • 1

    What error is it? any message appears?

  • 1

    What would be the mistake?

  • Added in publication

  • 1

    $uniforme is not an array, da a print_r() on it before Return.

  • I added print_r($even) to Function and error persists

  • 1

    Showed a blank array?

  • No, nothing has changed

  • 1

    Missed assignment, do so $uniformes = listaUniformes($conexao);

  • There, I added this code before the foreach, my Ide took out Highlight reporting an error but the page keeps reporting the Foreach error

  • 1

    is array_push a function? Where Returns?

  • I added the array_push in the function that captures the products in the database to insert what was assigned by the $uniform variable to the $uniform array

Show 6 more comments

1 answer

2


Your function returns the wrong value should return $uniformes and not $uniforme

Change:

return $uniforme;

To:

return $uniforme;

Remember to create a variable or pass an array to foreach, you can do it as follows:

<?php
   foreach(listaUniformes($conexao) as $uniforme) {

Or:

<?php
   $arr = listaUniformes($conexao);
   foreach($arr as $uniforme) {
  • Thank you very much but I was left with a doubt, if the function already returns $uniforms why I can’t put foreach($even the $uniform)?

  • 1

    @Luhansalimena the function does not return any variable by default are always values. After the function is over all variables declared within it are out of focus or else no longer exist. In this case you take the return (value) and assign it to a new variable that is outside the function scope.

  • Got it, thank you very much :D

Browser other questions tagged

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