Home >Database >Mysql Tutorial >How to Fetch Column Values into an Array Using PHP?

How to Fetch Column Values into an Array Using PHP?

Barbara Streisand
Barbara StreisandOriginal
2024-11-03 18:42:02460browse

How to Fetch Column Values into an Array Using PHP?

Retrieving Column Values into an Array Using PHP

Question:

How can I obtain all values within a specific column of a MySQL table and store them in an array using PHP?

Solution:

To achieve this, you can utilize either PDO or mysqli with PHP. Here's a breakdown of both approaches:

Using PDO:

<code class="php">$stmt = $pdo->prepare("SELECT Column FROM foo");
// Note: Using a LIMIT clause is advised for large tables to avoid performance issues.
$stmt->execute();
$array = $stmt->fetchAll(PDO::FETCH_COLUMN);
print_r($array);</code>

Using mysqli:

<code class="php">$stmt = $mysqli->prepare("SELECT Column FROM foo");
$stmt->execute();
$array = [];
foreach ($stmt->get_result() as $row) {
    $array[] = $row['column'];
}
print_r($array);</code>

Example Output:

Array
(
    [0] => 7960
    [1] => 7972
    [2] => 8028
    [3] => 8082
    [4] => 8233
)

The above is the detailed content of How to Fetch Column Values into an Array Using PHP?. 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