Home > Database > Mysql Tutorial > 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
Release: 2024-11-03 05:09:02
Original
904 people have browsed it

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>
Copy after login

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!

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