Home > Database > Mysql Tutorial > body text

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

Linda Hamilton
Release: 2024-11-17 13:48:01
Original
559 people have browsed it

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);
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template