PHP PDO 方法来获取匹配元素的简单列表 [英] PHP PDO method to fetch simple list of matched elements

查看:41
本文介绍了PHP PDO 方法来获取匹配元素的简单列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 PHP PDO 获取元素列表的最简单方法是什么?fetch 和 fetch 参数太多,我不确定哪个是正确的.

What is the most simple way to fetch a list of elements using PHP PDO? There are so many fetch and fetch parameters that I'm not sure which is the right one.

表用户

| id | username | age |
-----------------------
| 5  |  Joey    | 33  |
| 6  | Terry    | 44  |
| 7  | Billy    | 44  |

查询

$q = "SELECT username FROM Users WHERE age = 44";
$db->prepare($q)->execute();
$res = $db->fetch??(PDO::??);
echo json_encode($res);
// Should return, ideally, {"Terry", "Billy"}

如果我使用 fetchColumn,我似乎只会得到一个结果.如果我将 fetchAll 与 assoc_array 一起使用,那么如果可以避免的话,我不想遍历数组.

If I use fetchColumn I seem to just get one result. If I use fetchAll with assoc_array, well I don't want to iterate over the array if I can avoid it.

推荐答案

我最终使用了

$res = $stmt->fetchAll(PDO::FETCH_COLUMN);
return implode(",", $res);

这篇关于PHP PDO 方法来获取匹配元素的简单列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆