You can use a foreach of a query within a function

Asked

Viewed 360 times

1

I have a query simple:

$Consulta = $pdo->query(" SELECT * FROM dados ")->fetchAll();
foreach ($Consulta as $key) 
{
     echo $key["InfoDado"];
}

If you execute the foreach of it out of a function! beauty! Works as it should!

But I tried to execute that foreach inside a function and gave error!

You can run this foreach within a function? Something like:

function ExecutarForeach()
{
    foreach ($Consulta as $key) {
        echo $key["InfoDado"];
    }
};

ExecutarForeach();
  • 1

    You will have to pass the variable $Consulta for the function. function ExecutarForeach($Consulta) {...}

  • @stderr It worked brother! Thank you!

1 answer

3


As mentioned in commenting, you can pass the variable $consulta as an argument:

function executarForeach($consulta) {
    foreach ($consulta as $key) {
       echo $key["InfoDado"];
    }
}

And to call the function, do so:

$consulta = $pdo->query(" SELECT * FROM dados ")->fetchAll();

if ($consulta !== FALSE) {
   executarForeach($consulta);
}
else {
   // Consulta falhou...
}
  • 1

    Much simpler than I could imagine!

Browser other questions tagged

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