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!