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

How to Retrieve Single Column Values as Arrays with MySQLi?

Susan Sarandon
Susan SarandonOriginal
2024-11-02 04:07:03782browse

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>

Execute the query:

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

Then, modify your loop to use fetch_assoc():

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

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>

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!

Statement:
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