首页  >  文章  >  数据库  >  如何使用 PDO 将单列数据检索到一维数组中?

如何使用 PDO 将单列数据检索到一维数组中?

Patricia Arquette
Patricia Arquette原创
2024-11-13 13:38:02737浏览

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']

以上是如何使用 PDO 将单列数据检索到一维数组中?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn