Home >Database >Mysql Tutorial >How to Retrieve Column Values into an Array in PHP?
Retrieving Column Values into an Array in PHP
MySQL provides a vast array of data manipulation functions, including the ability to retrieve data from specific columns. In PHP, there are several approaches to accomplish this task.
One method involves using the PHP Database Object (PDO) extension. PDO offers a flexible and object-oriented interface for interacting with relational databases. To retrieve column values using PDO, you can utilize the following steps:
Prepare an SQL statement:
$stmt = $pdo->prepare("SELECT Column FROM foo");
Execute the prepared statement:
$stmt->execute();
Fetch all values from the result:
$array = $stmt->fetchAll(PDO::FETCH_COLUMN);
Print the array contents:
print_r($array);
Another approach to retrieve column values is by employing the MySQL Improved (mysqli) extension. This extension provides a procedural interface for interacting with MySQL databases. To achieve this:
Prepare an SQL statement:
$stmt = $mysqli->prepare("SELECT Column FROM foo");
Execute the prepared statement:
$stmt->execute();
Iterate over the result to collect column values:
$array = []; foreach ($stmt->get_result() as $row) { $array[] = $row['column']; }
Print the array contents:
print_r($array);
By implementing either of these approaches, you can efficiently retrieve values from a specific column in a MySQL database and store them in an array for further processing.
The above is the detailed content of How to Retrieve Column Values into an Array in PHP?. For more information, please follow other related articles on the PHP Chinese website!