在不知道字段的情况下循环 fetchall php

Loop through fetchall without knowing the fields php

我有一个简单的查询,它将从用户表中获取所有内容

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

然后我会有一个像

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

但是有没有一种不用写每个字段名就可以显示每个字段的方法呢?

首先,修复 return fetchAll 以指定 return 样式,如下所示:

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

然后您可以像这样在外部循环中使用内部循环:

//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>";
    }
}

这将输出所有列及其值,而不管数组中有哪些列。在注释之后,您可以看到我所做的是使用您的代码循环遍历外部数组,该数组是查询中每一行的数组。然后从每一行遍历数组,获取列名和该列中的值。现在我只是回显列和值。您可能想要做更多的事情,例如将此回显到 table 或任何您的最终目标。