Home > Backend Development > PHP Tutorial > How to Access Individual Columns from a MySQL Query Result?

How to Access Individual Columns from a MySQL Query Result?

Patricia Arquette
Release: 2024-10-30 21:25:30
Original
329 people have browsed it

How to Access Individual Columns from a MySQL Query Result?

Accessing Individual Columns from a MySQL Query

In MySQL, the mysqli_fetch_array() function can be used to retrieve rows from a query result as an associative array. However, when iterating over multiple rows, it's common to encounter an issue where all the columns from a given row are combined into a single array element.

Solution:

To address this and access the columns separately, you can utilize the following approach:

<code class="php">$posts = [];

while ($row = mysqli_fetch_array($result)) {
  $posts[] = array(
    'post_id'   => $row['post_id'],
    'post_title' => $row['post_title'],
    'content'    => $row['content'],
    // Add additional columns as needed...
  );
}</code>
Copy after login

With this modified code:

  • The $posts array now stores each row as an associative array, with column names as array keys.
  • You can access individual columns by accessing specific keys within the nested array. For instance, $posts[0]['post_id'] would retrieve the first post's ID.

By utilizing this approach, you can efficiently iterate over multiple rows in a query result and access the columns individually, enabling you to manipulate and process the data as desired.

The above is the detailed content of How to Access Individual Columns from a MySQL Query Result?. 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