Home  >  Article  >  Database  >  Why Do I Get Duplicate Values When Using mysql_fetch_array?

Why Do I Get Duplicate Values When Using mysql_fetch_array?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-02 05:01:30805browse

Why Do I Get Duplicate Values When Using mysql_fetch_array?

Duplicate Values in Array Returned by mysql_fetch_array

Question:

When fetching data from a MySQL table using mysql_fetch_array, double values are being returned, resulting in duplicate output when iterated through the array.

Example:

<code class="php"><?php
$table = get_personel_table(1);

function get_personel_table($id)
{
    global $connection;
    $query  = "SELECT * ";
    $query .= "FROM employees ";
    $query .= "WHERE id=" . $id . " ";
    $query .= "ORDER BY id ASC";
    $query_result = mysql_query( $query , $connection );
    confirm_query($query_result);
    $query_result_array = mysql_fetch_array($query_result);
    return $query_result_array; // returns associative array!;
}

foreach($table as $table_var)
{
    echo "<td>" . $table_var . "</td>";
} 
// Output:
// "1 1 1 1 jordan jordan 9108121544 9108121544  testEmail testEmail testAddress testAddress testCounty  testCounty"</code>

Why Does This Happen?

The mysql_fetch_array function returns an array that contains both associative and numeric indexes by default. This means that both the column names and the column indices (0, 1, 2, etc.) are used as keys.

Solution:

To prevent duplicate values, use the second parameter of mysql_fetch_array to specify which type of indexing you want. You can choose between numerical indexes only, associative indexes only, or both.

<code class="php">// Numerical indexes only
$query_result_array = mysql_fetch_array($query_result, MYSQL_NUM); 

// Associative indexes 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 fetch data with only numerical or associative indexes, respectively.

<code class="php">// Numerical indexes only
$query_result_array = mysql_fetch_row($query_result); 

// Associative indexes only
$query_result_array = mysql_fetch_assoc($query_result); </code>

The above is the detailed content of Why Do I Get Duplicate Values 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