PDO将表格中的一列取入一维数组 [英] PDO fetch one column from table into 1-dimensional array

查看:141
本文介绍了PDO将表格中的一列取入一维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对PDO相当陌生,并且让它们与MySQL一起使用.我似乎可以插入新数据并检索单个结果,但是我对此仍然坚持.

I'm fairly new to PDO and getting them to work with MySQL. I seem to be getting on alright with inserting new data and retriving single results however this I am stuck with.

我有一个由成分组成的表格,我正在尝试将所有成分组成一个数组.

I have a table that is made up of ingredients, I'm trying to make all the ingredients into a single array.

我已经直接将查询运行到SQL中,它向我显示了所有结果,但是使用PDO,仅凭fetch就无法获得此结果.当我使用下面的fetchAll方法时,它会为我提供所有结果,但是是多维数组而不是数组.

I've run the query directly into SQL and it shows me all the results, yet with PDO I can not get this with the just a fetch. When I use the fetchAll approach as below it gives me all the results but in a multidimensional array rather than just an array.

是否有单独的fetch方法,还是必须创建一个将结果添加到$a[]的循环?

Is there a seperate fetch method or do I have to create a loop which adds the results into $a[]?

$ingredient_q = "SELECT
        `ingredient_name`
         FROM
            `ingredients`
        ";

$ingredient_stmt = $pdo->query($ingredient_q);

$ingredient_stmt ->setFetchMode(PDO::FETCH_ASSOC);

$a = $ingredient_stmt->fetchAll();

我尝试过的事情:

$a = $ingredient_stmt->fetchAll(); // Returns a multidimensional array (not what I want)
$a = $ingredient_stmt->fetch(); // Returns one single result (the first entry)
$a[] = $ingredient_stmt->fetch(); // Returns one single result but in a multidimensional array.

任何帮助将不胜感激.

推荐答案

<?php
$sql = "SELECT `ingredient_name` FROM `ingredients`";
$ingredients = $pdo->query($sql)->fetchAll(PDO::FETCH_COLUMN);

这篇关于PDO将表格中的一列取入一维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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