Home > Database > Mysql Tutorial > body text

Why Does My MySQLi Fetch Array Result in Doubled Output?

DDD
Release: 2024-10-29 05:35:31
Original
1051 people have browsed it

Why Does My MySQLi Fetch Array Result in Doubled Output?

Double Results in Array (MySQLi Fetch Array)

Problem

Executing the following code:

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

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

foreach($table as $table_var) {
    echo "<td>$table_var</td>";
}</code>
Copy after login

results in doubled output, such as:

1 1   1   1   jordan  jordan  9108121544  9108121544  testEmail   testEmail   testAddress testAddress testCounty  testCounty
Copy after login

Solution

The default behavior of mysqli_fetch_array is to return both associative and numeric indexes for the result row. This is undesirable in the given situation. To limit the returned keys, you can use the second parameter of the function:

<code class="php">$query_result_array = mysqli_fetch_array($query_result, MYSQLI_NUM); // numeric keys only
$query_result_array = mysqli_fetch_array($query_result, MYSQLI_ASSOC); // associative keys only</code>
Copy after login

Alternatively, you can use the following functions:

<code class="php">$query_result_array = mysqli_fetch_row($query_result); // numeric keys only
$query_result_array = mysqli_fetch_assoc($query_result); // associative keys only</code>
Copy after login

By using numerical or associative keys only, you can eliminate the duplication of data in the output.

The above is the detailed content of Why Does My MySQLi Fetch Array Result in Doubled Output?. 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