Home >Database >Mysql Tutorial >Why does my foreach loop display doubled data when using `mysql_fetch_array`?

Why does my foreach loop display doubled data when using `mysql_fetch_array`?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-27 20:25:30922browse

Why does my foreach loop display doubled data when using `mysql_fetch_array`?

Doubled Results in Array (mysql_fetch_array)

The given code encounters an issue where the foreach loop displays doubled data due to the way mysql_fetch_array operates. By default, it assigns both numeric and associative indexes to each element in the result array. This effect can be observed in the print_r output, where both indexes (0, 1, 2, etc.) and their corresponding keys (id, department_id, name, etc.) appear.

To resolve this issue, you can specify the type of indexes you want in the mysql_fetch_array function call. By passing MYSQL_NUM as the second parameter, you can retrieve an array with only numeric keys. Alternatively, MYSQL_ASSOC will return an array with only associative keys.

<code class="php">// Get numeric keys only
$query_result_array = mysql_fetch_array($query_result, MYSQL_NUM);

// Get associative keys only
$query_result_array = mysql_fetch_array($query_result, MYSQL_ASSOC);</code>

You can also use the mysql_fetch_row and mysql_fetch_assoc functions, which specifically return numeric or associative arrays, respectively:

<code class="php">// Get numeric keys only
$query_result_array = mysql_fetch_row($query_result);

// Get associative keys only
$query_result_array = mysql_fetch_assoc($query_result);</code>

By utilizing these options, you can avoid duplicated data in your foreach loop and ensure that the resulting array contains the indexes and values that you need.

The above is the detailed content of Why does my foreach loop display doubled data when using `mysql_fetch_array`?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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