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!