Home > Database > Mysql Tutorial > body text

How to Extract Column Values into an Array Using PHP?

Patricia Arquette
Release: 2024-11-02 14:27:02
Original
861 people have browsed it

How to Extract Column Values into an Array Using PHP?

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

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

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

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!

source:php.cn
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