在使用以下内容时:
$db = new PDO(connection_details)
$query = "SELECT * FROM vservers LIMIT 5";
$result = $db->query($query);然后试着和then f.e取得记录。
while ($row = $result->fetchAll(PDO::FETCH_OBJ)) {
var_dump($row);
}它使用StdObjects返回一个数组,如下所示:
array (size=5)
0 =>
object(stdClass)[3]
public 'vserverid' => string '898' (length=3)
public 'templatename' => string 'Debian' (length=14)
public 'template' => string 'debian-7.0-x86' (length=14)
1 =>
object(stdClass)[4]
public 'vserverid' => string '792' (length=3)
public 'templatename' => string 'Ubuntu' (length=33)
public 'template' => string 'ubuntu-15.04' (length=27)使用foreach,它返回StdObjects
foreach ($result->fetchAll(PDO::FETCH_OBJ) as $key) {
var_dump($key);
}
object(stdClass)[3]
public 'vserverid' => string '898' (length=3)
public 'templatename' => string 'Debian' (length=6)
public 'template' => string 'debian' (length=6)
object(stdClass)[4]
public 'vserverid' => string '792' (length=3)
public 'templatename' => string 'Ubuntu' (length=6)
public 'template' => string 'ubuntu' (length=6)有人能解释一下这种行为吗?通常,我希望返回像foreach这样的对象,但是这是一个好的实践吗?
发布于 2016-10-14 21:58:04
fetchAll()以数组的形式返回所有结果,其中每个元素都是表示表中一行的对象。
在while代码中,第一个迭代将$row设置为整个结果集,并将其作为一个数组转储。只有一次迭代,因为下一次对fetchAll()的调用返回一个空数组,因为没有什么可获取的了。
在foreach代码中,fetchAll()将数组返回给foreach,然后foreach每次迭代一个元素,将$key设置为每个对象。然后你把那个东西扔进你的身体里。
通常,当您使用while时,您使用的是fetch(),而不是fetchAll()。此代码将等效于foreach
while ($key = $result->fetch(PDO::FETCH_OBJ)) {
var_dump($key);
}https://stackoverflow.com/questions/40052503
复制相似问题