这个对 MySQL 的查询:
SELECT `group_id`
FROM `j30_user_usergroup_map`
WHERE `user_id` =3065
正在返回以下结果:
但是,在 PHP 中有以下代码:
$db = new PDO('mysql:host=localhost;dbname=', '', '');
$sth = $db->prepare('SELECT `group_id`
FROM `j30_user_usergroup_map`
WHERE `user_id` =3065');
$sth->execute();
$result = $sth->fetch(PDO::FETCH_ASSOC);
print_r($result);
正在返回:
( [group_id] => 2 )
我想要数组的所有元素,而不仅仅是第一个元素,如所述here
最佳答案
您有两种方法可以解决这个问题,将 fetch()
更改为 fetchAll()
或使用 while
并返回一个新数组。
1) FetchAll 方法
改变:
$result = $sth->fetch(PDO::FETCH_ASSOC);
通过:
$result = $sth->fetchAll(PDO::FETCH_ASSOC);
2) 接近
$items = array();
while($row = $sth->fetch(PDO::FETCH_ASSOC)){
$items[] = $row;
}
关于php - fetch(PDO::FETCH_ASSOC) 将 MySQL 查询的所有值返回到数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36722769/