Home > Database > Mysql Tutorial > body text

Why is my `mysql_fetch_array` returning duplicate data?

DDD
Release: 2024-10-31 07:54:30
Original
402 people have browsed it

Why is my `mysql_fetch_array` returning duplicate data?

Double Results with mysql_fetch_array

In the provided code, you execute a query to fetch personnel data based on an ID and return the result as an associative array. However, when you iterate through the array and print its values, you encounter duplicate data.

This is because mysql_fetch_array retrieves both the associative and numeric keys by default. Each key-value pair is displayed twice, leading to the doubled output you observe.

Solution:

To retrieve only the associative keys, use mysql_fetch_assoc instead of mysql_fetch_array. By doing this, you will limit the returned array to only contain associative keys, matching the column names to the respective values. This will resolve the double output issue:

<code class="php">$query_result_array = mysql_fetch_assoc($query_result);</code>
Copy after login

Alternatively, you can specify the second parameter of mysql_fetch_array to retrieve either associative or numeric keys only:

<code class="php">$query_result_array = mysql_fetch_array($query_result, MYSQL_ASSOC); // associative keys only
$query_result_array = mysql_fetch_array($query_result, MYSQL_NUM); // numeric keys only</code>
Copy after login

By using mysql_fetch_assoc or setting the second parameter appropriately, you can eliminate the duplicate data and obtain a single instance of each value in the associative array.

The above is the detailed content of Why is my `mysql_fetch_array` returning duplicate data?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template