Home > Database > Mysql Tutorial > body text

Why do I get doubled results when using `mysql_fetch_array`?

DDD
Release: 2024-10-27 09:36:30
Original
202 people have browsed it

Why do I get doubled results when using `mysql_fetch_array`?

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>
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!