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>
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>
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!