Home > Database > Mysql Tutorial > How to Retrieve Single Column Values as a One-Dimensional Array with MySQLi?

How to Retrieve Single Column Values as a One-Dimensional Array with MySQLi?

Mary-Kate Olsen
Release: 2024-10-31 00:17:30
Original
793 people have browsed it

How to Retrieve Single Column Values as a One-Dimensional Array with MySQLi?

Retrieving Single Column Values with MySQLi

It can be challenging to retrieve data from a MySQL database and store it as a one-dimensional array. By default, MySQLi returns multidimensional arrays, as seen in the provided code snippet:

$query = "SELECT DISTINCT `EmailAddress` FROM `Emails` WHERE `JobID` = 1";
$result = $conn->query($query);
while ($row = $result->fetch_row()) {
    $rows[] = $row;
}
Copy after login

This code returns a multidimensional array with each row represented as a separate element. However, the goal is to obtain a one-dimensional array of email addresses.

Solution: Using fetch_assoc()

To rectify this issue, use fetch_assoc() instead of fetch_row(). fetch_assoc() retrieves the row as an associative array, where the column names serve as keys and the values are stored as elements. Here's the modified code:

while ($row = $result->fetch_assoc()) {
    $rows[] = $row['EmailAddress'];
}
Copy after login

By switching to fetch_assoc(), the code successfully stores the email addresses as a one-dimensional array, with each email address stored in its own element:

<code class="php">array(2) {
    [0] => "[email protected]"
    [1] => "[email protected]"
}</code>
Copy after login

The above is the detailed content of How to Retrieve Single Column Values as a One-Dimensional Array with MySQLi?. 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