如何使用 PDO 將單列資料檢索到一維數組?

Patricia Arquette
發布: 2024-11-13 13:38:02
原創
706 人瀏覽過

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中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板