简体   繁体   中英

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.

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

you have to foreach or while through your fetched rows:

foreach ($ingredient_stmt->fetchAll() as $row) {
var_dump($row);
}

while ($row = $ingredient_stmt->fetch()) {
var_dump($row);
}

both are kinda equivalent, foreach generates a bigger memory load as you're loading a bigger array, whereas while gets one row at a time

notice how to use fetch and fetchAll ; the former is for while, moving through each row one at a time, the latter is targeted to foreach, where the array must be known beforehand

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM