Home  >  Article  >  Database  >  How to Retrieve a Single Column of Data into a 1-Dimensional Array Using PDO?

How to Retrieve a Single Column of Data into a 1-Dimensional Array Using PDO?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-13 13:38:02738browse

How to Retrieve a Single Column of Data into a 1-Dimensional Array Using PDO?

Retrieve a Single Column of Data into a 1-Dimensional Array Using PDO

PDO offers a versatile way to interact with MySQL databases, but extracting specific columns into a single array can sometimes be challenging. Here's a method to accomplish this effectively:

Query and Set Fetch Mode

First, construct your query and prepare a PDO statement as usual:

$sql = "SELECT `ingredient_name` FROM `ingredients`";
$statement = $pdo->query($sql);
$statement->setFetchMode(PDO::FETCH_ASSOC);

Use the fetchAll() Method

Instead of using the standard fetch() or fetchAll() methods, employ the fetchAll(PDO::FETCH_COLUMN) method to specify that you want only the specified column:

$ingredients = $statement->fetchAll(PDO::FETCH_COLUMN);

Explanation

By using PDO::FETCH_COLUMN, you instruct PDO to retrieve all values of the specified column (ingredient_name in this case) and store them in a 1-dimensional array named $ingredients. This array will contain only the ingredient names.

Example

For instance, if your ingredients table contains the following ingredient names:

ingredient_name
Flour
Sugar
Eggs

The $ingredients array will have the following elements:

['Flour', 'Sugar', 'Eggs']

The above is the detailed content of How to Retrieve a Single Column of Data into a 1-Dimensional Array Using PDO?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn