PDO fetch one column from table into 1-dimensional array

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

Related videos on Youtube

SamesJeabrook
Author by

SamesJeabrook

"Self taught" meaning I asked a lot of questions on Stack Overflow to learn code

Updated on August 24, 2020

Comments

  • SamesJeabrook
    SamesJeabrook over 3 years

    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.

    • AbraCadaver
      AbraCadaver almost 10 years
      Multidimensional because you have multiple rows or a single dimension because you have a single row.
    • Marc B
      Marc B almost 10 years
      var_dump($a) will tell you what you're getting...
    • SamesJeabrook
      SamesJeabrook almost 10 years
      I don't understand, I'm trying to extract all results from a single row, so I assume with that that it would be a single dimension
    • Noah
      Noah almost 10 years
      Then you, my friend, want SELECT * FROM ingredients WHERE [Please put a condition here]. This is not at all related to PDO, PHP, or arrays, but your understanding of MySQL
    • Marcus Adams
      Marcus Adams almost 10 years
      possible duplicate of Loop results PDO PHP
    • AbraCadaver
      AbraCadaver almost 10 years
      If you have multiple rows in ingedients then you will get all rows with that query.
    • Your Common Sense
      Your Common Sense almost 10 years
      Now read the new title and think how fatally you can spoil your chance for the proper answer.