Home >Database >Mysql Tutorial >How to Fetch a Single Column from a Table into an Array Using PDO?

How to Fetch a Single Column from a Table into an Array Using PDO?

Linda Hamilton
Linda HamiltonOriginal
2024-11-17 13:48:01644browse

How to Fetch a Single Column from a Table into an Array Using PDO?

Retrieving a Single Column from a Table into an Array with PDO

While trying to retrieve ingredients from a database table into a single array using PDO, you may face challenges due to the multiple results returned by the query. The standard fetchAll() method yields a multidimensional array, which is not the desired format.

To address this, you can utilize the PDO::FETCH_COLUMN constant in the fetchAll() method. This constant instructs PDO to fetch only the specified column from each row, resulting in a one-dimensional array.

The following code demonstrates this approach:

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

This code will assign an array of ingredient names to the $ingredients variable, providing you with easy access to all ingredients in a single dimension.

The above is the detailed content of How to Fetch a Single Column from a Table into an 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