Home  >  Article  >  Backend Development  >  How can I access individual columns when using mysqli_fetch_array() in PHP?

How can I access individual columns when using mysqli_fetch_array() in PHP?

Susan Sarandon
Susan SarandonOriginal
2024-11-01 04:41:01798browse

How can I access individual columns when using mysqli_fetch_array() in PHP?

Fetching MySQL Query Results with mysqli_fetch_array

Issue

Trying to fetch query results using mysqli_fetch_array() but all columns are combined into a single column, making individual column access impossible. Assigning each column to a specific variable results in only one row being returned.

Solution

To retrieve all values from the MySQL query:

<code class="php">$posts = array();
while ($row = mysqli_fetch_array($result)) {
    $posts[] = $row;
}</code>

This assigns the entire row as an array element in the $posts array.

To access each value individually:

<code class="php">foreach ($posts as $row) {
    foreach ($row as $element) {
        echo $element . "<br>";
    }
}</code>

This nested loop iterates over the rows and columns, echoing each element.

Alternatively, you can access each element directly from the $post variable:

<code class="php">echo $post['post_id'];</code>

This retrieves the value of the 'post_id' column.

The above is the detailed content of How can I access individual columns when using mysqli_fetch_array() in PHP?. 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