PDO 从表中提取一列到一维数组中 [英] PDO fetch one column from table into 1-dimensional array

查看:16
本文介绍了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天全站免登陆