Doubled Results in Arrays Using mysql_fetch_array
When retrieving data from a MySQL database using mysql_fetch_array, it's possible to encounter doubled results. This occurs because by default, mysql_fetch_array returns both associative and numeric indexes for each row in the array.
Consider the following code:
<code class="php">$query_result_array = mysql_fetch_array($query_result);</code>
In this example, $query_result_array will contain both numeric and associative indexes. As a result, you will get double output when iterating over the array:
<code class="php">foreach($table as $table_var) { echo "<td>" . $table_var . "</td>"; } </code>
To avoid this, you can limit the type of indexes returned by using the second parameter of mysql_fetch_array:
<code class="php">// Numeric keys only $query_result_array = mysql_fetch_array($query_result, MYSQL_NUM); // Associative keys only $query_result_array = mysql_fetch_array($query_result, MYSQL_ASSOC);</code>
Alternatively, you can use the mysql_fetch_row and mysql_fetch_assoc functions to retrieve only numeric or associative keys, respectively:
<code class="php">// Numeric keys only $query_result_array = mysql_fetch_row($query_result); // Associative keys only $query_result_array = mysql_fetch_assoc($query_result);</code>
By using these techniques, you can ensure that your arrays contain only the desired type of indexes, preventing doubled results when iterating.
The above is the detailed content of Why do I get doubled results when using `mysql_fetch_array`?. For more information, please follow other related articles on the PHP Chinese website!