【发布时间】:2016-01-10 18:01:00
【问题描述】:
在获取查询之前,我需要一列的值。像这样的:
// mytable
+----+-------+
| id | codes |
+----+-------+
| 1 | 102 |
| 2 | 64 |
| 3 | 563 |
| 4 | 79 |
+----+-------+
我的查询:
$db = new PDO("mysql:host=localhost;dbname=mydb", "root", "");
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sth = $db->prepare("SELECT * FROM mytable");
$sth->execute();
/* I need to those numbers in the codes-column as an array in here */
while ($results = $sth->fetch()) {
var_dump($results);
}
那么,在上面的代码中,我如何在while() 之前访问这个数组[0]=>102, [1]=>64, [2]=>563, [3]=>79?
注意:最好不要使用fetchAll();
【问题讨论】:
-
好吧,您必须以某种方式获取它们……没有这些数据库功能,您就无法通过神奇的千里眼来获取它们。所以要么
fetchAll,要么基于fetch的第二个循环。 -
使用 fetchAll();并使用该数组将
while更改为foreach$results -
@splash58 我在某处读到
fetchAll()消耗大量内存。所以我担心使用它。 -
你为什么需要它?
-
如果你还是要使用 fetch 读取所有内容,那么在内存使用方面几乎没有什么区别。