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

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

Linda Hamilton
Release: 2024-10-31 09:09:02
Original
1008 people have browsed it

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

How do I obtain single column values as a one-dimensional array using MySQLi?

You encounter a predicament while attempting to retrieve a list of emails as a one-dimensional array from a MySQL database. Instead of the desired one-dimensional array, you receive a multidimensional array.

Solution:

The issue lies in the method used for fetching the data from the database. To retrieve the data as an array of single column values, you should use the fetch_assoc() method instead of fetch_row().

Here is a corrected code snippet:

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

By using fetch_assoc(), the while loop will iterate through the rows of the result set and fetch the value of the EmailAddress column for each row. The fetched values will be appended to the $rows array, resulting in a one-dimensional array containing the list of email addresses.

This revised code will produce the expected output:

array(2) {
  [0] => "[email protected]"
  [1] => "[email protected]"
}
Copy after login

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