php PDO fetchAll() - 虽然不工作,但 foreach 工作
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17729301/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
php PDO fetchAll() - while not working, foreach works
提问by Mafitsi
I would like to know if i'm doing fine OR fetchAll() doesn't work with WHILE.
我想知道我是否做得很好,或者 fetchAll() 不适用于 WHILE。
here is an exemple
这是一个例子
$db=new PDO("mysql:host=" .$dbhost. "; dbname=" . $dbname, $dbuser, $dbpass);
$page=$db->prepare("SELECT * FROM page");
$page->execute();
foreach ($page->fetchAll(PDO::FETCH_ASSOC) as $row) {
//echo a row
//is working
}
however, i if try looping with a while
但是,我如果尝试循环一段时间
while ($row=$page->fetchAll(PDO::FETCH_ASSOC)){
//echo a row
//Show empty
}
i tryed to use only fetch(), it was working, my question: why fetchAll() doesn't work with "WHILE" ?
我试图只使用 fetch(),它起作用了,我的问题是:为什么 fetchAll() 不适用于“WHILE”?
回答by Orangepill
Fetch all returns all of the records remaining in the result set. With this in mind your foreach is able to iterate over the result set as expected.
Fetch all 返回结果集中剩余的所有记录。考虑到这一点,您的 foreach 能够按预期迭代结果集。
For the equivalent while implementation should use $page->fetch(PDO::FETCH_ASSOC);
对于等效的 while 实现应该使用 $page->fetch(PDO::FETCH_ASSOC);
while ($row = $page->fetch(PDO::FETCH_ASSOC)){
// do something awesome with row
}
if you want to use a while and fetch all you can do
如果你想使用一段时间并获取所有你能做的
$rows = $page->fetchAll(PDO::FETCH_ASSOC);
// use array_shift to free up the memory associated with the record as we deal with it
while($row = array_shift($rows)){
// do something awesome with row
}
A word of warning though: fetch all will do exactly that, if the result size is large it will stress the resources on your machine. I would only do this if I know that the result set will be small, or I'm forcing that by applying a limit to the query.
不过有一句警告: fetch all 将完全做到这一点,如果结果大小很大,它会给您机器上的资源带来压力。我只会在我知道结果集很小的情况下这样做,或者我通过对查询应用限制来强制这样做。
回答by Tyler V.
From the PHP Manual:
来自 PHP 手册:
The meaning of a while statement is simple. It tells PHP to execute the nested statement(s) repeatedly, as long as the while expression evaluates to TRUE.
while 语句的含义很简单。它告诉 PHP 重复执行嵌套语句,只要 while 表达式的计算结果为 TRUE。
Since the method you're usingreturns an array,
while ($row=$page->fetchAll(PDO::FETCH_ASSOC))
is going to set $row to an array of the entire result set. What you're expecting is for the fetchAll method to extend the Iterator class, which it does not.
由于您使用的方法返回一个数组,
while ($row=$page->fetchAll(PDO::FETCH_ASSOC))
因此将 $row 设置为整个结果集的数组。您期望 fetchAll 方法扩展Iterator 类,但它没有。
A foreach
is the right way to go here.
Aforeach
是去这里的正确方式。
回答by michi
no need to loop through the recordset, because fetchAll
- well - fetches allthe records in one command. Nice, isn't it?
无需遍历记录集,因为fetchAll
- 好吧 -在一个命令中获取所有记录。不错,不是吗?
$rows = $page->fetchAll(PDO::FETCH_ASSOC);
// $rows is an array containing all records...
foreach ($rows as $row)
echo $row->fieldname;
回答by user4035
I tried to reproduce your case. Look here:
我试图重现你的情况。看这里:
script.php
脚本文件
<?php
$host = 'localhost';
$user = "user";
$password = '';
$db_name = 'test';
$port = 3306;
try
{
$connection = new PDO("mysql:host=$host;port=$port;dbname=$db_name", $user, $password);
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e)
{
echo 'Connection failed: ' . $e->getMessage();
}
$page=$connection->prepare("SELECT * FROM Document");
$page->execute();
while ($row = $page->fetchAll(PDO::FETCH_ASSOC)) {
var_dump($row);
}
Database test
数据库测试
DROP TABLE IF EXISTS `Document`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Document` (
`DataID` int(10) unsigned NOT NULL AUTO_INCREMENT,
`Description` varchar(50) CHARACTER SET utf8 NOT NULL,
PRIMARY KEY (`DataID`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `Document`
--
LOCK TABLES `Document` WRITE;
/*!40000 ALTER TABLE `Document` DISABLE KEYS */;
INSERT INTO `Document` VALUES (1,'!!!'),(2,'This is document 2'),(3,'This is document 3'),(4,'This is document 4'),(5,'Hello');
/*!40000 ALTER TABLE `Document` ENABLE KEYS */;
UNLOCK TABLES;
output
输出
$php script.php
array(5) {
[0]=>
array(2) {
["DataID"]=>
string(1) "1"
["Description"]=>
string(3) "!!!"
}
[1]=>
array(2) {
["DataID"]=>
string(1) "2"
["Description"]=>
string(18) "This is document 2"
}
[2]=>
array(2) {
["DataID"]=>
string(1) "3"
["Description"]=>
string(18) "This is document 3"
}
[3]=>
array(2) {
["DataID"]=>
string(1) "4"
["Description"]=>
string(18) "This is document 4"
}
[4]=>
array(2) {
["DataID"]=>
string(1) "5"
["Description"]=>
string(5) "Hello"
}
}
The output means, that while statement was executed once and prints all the rows, that the query should return, which is absolutely correct, because fetchAll returns an array of arrays with all the rows. PHP interprets it as true and while runs once.
输出意味着,while 语句执行一次并打印所有行,查询应该返回,这是绝对正确的,因为 fetchAll 返回一个包含所有行的数组。PHP 将其解释为 true 并且 while 运行一次。
While foreach
will iterate over the array of arrays and you will have the corresponding row every time.
虽然foreach
将遍历数组数组,并且每次都会有相应的行。
回答by bansi
With fetchAll
In while loop you have fetched all records in the first iteration and there is nothing to fetch the next time. In foreach
also you have fetched all records in the first line, but foreach
uses the result for iteration.
使用fetchAll
In while 循环,您已经在第一次迭代中获取了所有记录,并且下次没有任何内容可获取。在foreach
你也已经赚得了第一行中的所有记录,但foreach
使用结果进行迭代。