0

Say I have an array which fetched a single row from my database via the PDO::FETCH_ASSOC method, which I would then assign to a variable like so:

$result = $stmt->fetch(PDO::FETCH_ASSOC);

$result now holds an array equal to the following:

Array ( 
  [id] => 42
)

So, to assign the value 'id' to a variable by itself, I then have to go:

$id = $result['id'];

Is there a quicker way to do this, or even better, to make sure the query result from my database is a variable rather than an array directly, assuming the query is always guaranteed to return 1 result?

4

2 回答 2

1

在 PHP >= 5.4 中,尝试

$result = $stmt->fetch(PDO::FETCH_ASSOC)[0];

这是一个猜测,但是,您必须对其进行测试。

于 2013-08-19T09:03:35.447 回答
1

这应该可以解决问题

$result = $stmt->fetchColumn();

文档在这里(只是注意到马克贝克也在他的评论中提到)。

于 2013-08-19T09:05:25.233 回答