Home  >  Article  >  Database  >  How to Retrieve Single Column Values as a One-Dimensional Array using MySQLi?

How to Retrieve Single Column Values as a One-Dimensional Array using MySQLi?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-03 05:09:02799browse

How to Retrieve Single Column Values as a One-Dimensional Array using MySQLi?

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!

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