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']; }
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]" }
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!