Getting Single Column Values with MySQLi
When retrieving data from a MySQL database using MySQLi, it's sometimes necessary to extract values from a specific column into a one-dimensional array. However, developers often encounter an issue where the result is a multidimensional array.
To address this issue, it's recommended to use the fetch_assoc() method instead of fetch_row(). This method returns an associative array where the column names are used as keys, providing a direct and convenient way to access individual column values:
<code class="php"><?php $conn = new mysqli("localhost", "username", "password", "database"); if (!$conn) { printf("Could not connect to database: %s\n", $mysqli->error); exit; } $query = "SELECT DISTINCT `EmailAddress` FROM `Emails` WHERE `JobID` = 1"; $result = $conn->query($query); if (!$result) { printf("Query failed: %s\n", $mysqli->error); exit; } while ($row = $result->fetch_assoc()) { $rows[] = $row['EmailAddress']; } $result->close(); $conn->close(); var_dump($rows); // Output: array(2) { [0] => "username@example.com", [1] => "username2@example.com" } ?></code>
By using fetch_assoc(), the result will be a one-dimensional array containing only the values from the specified column. This simplifies the data retrieval process and ensures the desired output.
The above is the detailed content of How to Retrieve Single Column Values as a One-Dimensional Array using MySQLi?. For more information, please follow other related articles on the PHP Chinese website!