Home > Database > Mysql Tutorial > How to Retrieve Single Column Values as Arrays with MySQLi?

How to Retrieve Single Column Values as Arrays with MySQLi?

Susan Sarandon
Release: 2024-11-02 04:07:03
Original
858 people have browsed it

How to Retrieve Single Column Values as Arrays with MySQLi?

Retrieve Single Column Values as Arrays with MySQLi

In certain situations, you may need to retrieve specific data from a database as a one-dimensional array. While the fetch_row() method in MySQLi can retrieve data as a multidimensional array, it's possible to obtain a simpler format.

To accomplish this, consider using the fetch_assoc() method instead. This method returns an associative array where column names serve as keys and the corresponding values are stored.

Suppose you have a query that retrieves distinct email addresses from a table:

<code class="php">$query = "SELECT DISTINCT `EmailAddress` FROM `Emails` WHERE `JobID` = 1";</code>
Copy after login

Execute the query:

<code class="php">$result = $conn->query($query);</code>
Copy after login

Then, modify your loop to use fetch_assoc():

<code class="php">while($row = $result->fetch_assoc()) {
  $rows[] = $row['EmailAddress'];
}</code>
Copy after login

By referencing the column name ('EmailAddress') in the fetch_assoc() method, you're extracting the value and storing it in a one-dimensional array called $rows.

After executing this loop, the $rows array will contain the list of emails in the specified format:

<code class="php">array(
  "[email protected]",
  "[email protected]"
)</code>
Copy after login

This simplified array structure aligns with your desired output and avoids the multidimensional format that fetch_row() would provide.

The above is the detailed content of How to Retrieve Single Column Values as Arrays 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