Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
527 views
in Technique[技术] by (71.8m points)

php - PDO fetch one column from table into 1-dimensional array

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.

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.

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();

Things I've tried:

$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.

Any help will be greatly appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
<?php
$sql = "SELECT `ingredient_name` FROM `ingredients`";
$ingredients = $pdo->query($sql)->fetchAll(PDO::FETCH_COLUMN);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...