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

Susan Sarandon
Release: 2024-11-01 04:41:01
Original
850 people have browsed it

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

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

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

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!

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