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
Release: 2024-11-03 18:42:02
Original
437 people have browsed it

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

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

Example Output:

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

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