Search code examples
phppdoforeachfetchall

Loop through fetchall without knowing the fields php


I have a simple query which will fetch all from a users tables

$query = $this->pdo->prepare('SELECT * FROM `users`');
$query->execute();
return $query->fetchAll();

Then i would have a foreach loop like

$results = $User->getUser();
foreach($results as $result){
echo $result['fname'];
echo $result['lname'];
}

But is there a way to display each of the fields without writing each field name?


Solution

  • First, fix your return fetchAll to specify the return style like so:

    return $query->fetchAll(PDO::FETCH_ASSOC);
    

    Then you can use an inner loop with your outter loop like so:

    //get the results
    $results = $User->getUser();
    //loop over the results, setting $result to an array representing each row
    foreach($results as $result){
        //loop over each $result (row), setting $key to the column name and $value to the value in the column.
        foreach($result as $key=>$value){
            //echo the key and value.
            echo "{$key} = {$value}<br>";
        }
    }
    

    This will output all columns and their value regardless of what columns there are in the array. Following the comments, you can see what I do is, using your code, loop over the outer array that is an array of each row from the query. Then loop over the array from each row getting the column name and the value in that column. For now I am just echo'ing out the column and value. You would likely want to do more like echo this out to a table or whatever your end goal is.