【问题标题】:How to access column-values before fetching?如何在获取之前访问列值?
【发布时间】: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 读取所有内容,那么在内存使用方面几乎没有什么区别。

标签: php mysql pdo


【解决方案1】:

您的问题就像是在说 如何在不获取数据的情况下获取数据?

这显然是不可能的,您需要在应用程序中的某个时间点获取它。


if($results = $sth->fetch()) {
    var_dump($results);
}

【讨论】:

  • 好的,您对此有何看法:如何仅获取查询结果的一列?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-20
  • 2010-11-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多