How to Extract Column Values into an Array using PHP
In databases, it's often useful to access specific columns and store their values in an array for analysis or manipulation. In PHP, obtaining all values from a MySQL column is straightforward.
Using PDO
PDO (PHP Data Objects) is a popular PHP extension for database connectivity. To get column values using PDO, follow these steps:
<code class="php">$dsn = 'mysql:dbname=database_name;host=localhost'; $username = 'database_user'; $password = 'database_password'; $pdo = new PDO($dsn, $username, $password); $stmt = $pdo->prepare("SELECT column_name FROM table_name"); $stmt->execute(); $array = $stmt->fetchAll(PDO::FETCH_COLUMN); print_r($array); // Output the array</code>
Using MySQLi
MySQLi is another extension for PHP that provides MySQL database access. Here's how to retrieve column values using MySQLi:
<code class="php">$servername = 'localhost'; $username = 'database_user'; $password = 'database_password'; $dbname = 'database_name'; $mysqli = new mysqli($servername, $username, $password, $dbname); $stmt = $mysqli->prepare("SELECT column_name FROM table_name"); $stmt->execute(); $array = []; foreach ($stmt->get_result() as $row) { $array[] = $row['column_name']; } print_r($array); // Output the array</code>
Example Output
For a table with the following data:
ID | Name |
---|---|
1 | John |
2 | Mary |
3 | Tom |
The resulting array would be:
Array ( [0] => John [1] => Mary [2] => Tom )
The above is the detailed content of How to Extract Column Values into an Array Using PHP?. For more information, please follow other related articles on the PHP Chinese website!