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>
results in doubled output, such as:
1 1 1 1 jordan jordan 9108121544 9108121544 testEmail testEmail testAddress testAddress testCounty testCounty
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>
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>
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!