Ryan
Ryan

Reputation: 985

PHP Function producing two iterations of an array, in the same array

I've got a function that gets data from a NoSQL database, and if it's not available then it goes to a MySQL database to get the data but the issue is, the function is putting the data into the array twice and I can't figure out why.

Expected result

array(2) { 
["id"]=> string(2) "30" 
["username"]=> string(8) "Username" }

Actual result

array(4) { 
[0]=> string(2) "30" 
["id"]=> string(2) "30" 
[1]=> string(8) "Username" 
["username"]=> string(8) "Username" }

Code

Code that is irrelevant to the problem is removed and replaced by pseudo code comments.

        $Connection = $this->Connect("MySQLi");
        $Data = MySQLi_Fetch_Array(

            MySQLi_Query($Connection["MySQLi"], $Options["Query"])

        );

        echo "Got array (MySQLi).";

It's worth noting that the string "Got array (MySQLi)." only appears once.

Upvotes: 1

Views: 34

Answers (2)

Joachim Isaksson
Joachim Isaksson

Reputation: 181027

mysqli_fetch_array() takes a parameter, resulttype, which by default is set to MYSQLI_BOTH.

By using the MYSQLI_ASSOC constant this function will behave identically to the mysqli_fetch_assoc(), while MYSQLI_NUM will behave identically to the mysqli_fetch_row() function. The final option MYSQLI_BOTH will create a single array with the attributes of both.

mysqli_fetch_assoc fetches an associative array, while mysqli_fetch_row fetches an array with numeric indexes.

mysqli_fetch_array with the parameter MYSQLI_BOTH will fetch both named (associative) indexes and numeric indexes in the same array.

Upvotes: 1

Jerzy Zawadzki
Jerzy Zawadzki

Reputation: 1985

MySQLi_Fetch_Array gets duplicated data in one array - with numerical and associative indexes at the same time

Use mysqli_fetch_assoc instead to have only associative

Upvotes: 2

Related Questions