user7236046
user7236046

Reputation:

Why is my array returning duplicate information?

I'm somewhat new to PHP's PDO and getting my head around why it's doing something a bit strange. I have the following code (works as intended).

$db = new Database;

$query = $db->prepare( 'SELECT * FROM users WHERE id = :value LIMIT 1' );

$query->bindParam( ':value', $value );

$query->execute();

$result = $query->fetch();

However, I'm curious as to why it's returning a seemingly duplicated response. This is an example of what it returns:

/file.php:X:
array (size=X)
  'id' => string '2' (length=1)
  0 => string '2' (length=1)
  'fullname' => string '' (length=0)
  1 => string '' (length=0)
  'email' => string '[email protected]' (length=15)
  2 => string '[email protected]' (length=15)
...

I have columns in my database for ID, fullname and email etc etc, but why is it also returning key value pairs twice where the second one defaults to an int based key?

Upvotes: 0

Views: 49

Answers (1)

ThS
ThS

Reputation: 4783

You didn't specify the desired fetching style, and by default it's set to PDO::FETCH_BOTH and that's why you get duplicate data. So You need to specify the desired style of the returned array(either indexed by number or by string, aka associative array, or object...), you need to change this line:

$result = $query->fetch();

into this to fetch an associative array:

$result = $query->fetch(PDO::FETCH_ASSOC);

Or this to fetch a classic array indexed by numbers beginning from 0:

$result = $query->fetch(PDO::FETCH_NUM);

There are more fetching styles, you can see the php manual for more informations pdo fetch method

Hope I pushed you further.

Upvotes: 1

Related Questions