views:

36

answers:

4

My MySQL queries are returning arrays with duplicate entries: numbered keys and labeled keys with the same data inside. This may be standard, but it seems like a waste, and something that could cause problems if I'm printing values. I mean, not a huge problem, obviously. But I'm just curious if I can stop that. It seems unnecessary. For example:

Array(
    [0] => "Ted",
    [first_name] => "Ted",
    [1] => "Schmidlap",
    [last_name] => "Schmidlap"
)

And so on.

I'm pretty new to a lot of this, so this may be a simple question, but Googling doesn't seem to have any answers for me. Anyone know the reason this happens? I'm using PHP's PDO now, but I was doing it straight through the MySQL functions before and the same thing was happening, so I assume it's a byproduct of MySQL interaction.

I can iterate through and unset the numeric ones, because I don't need them, but they're not really in the way right now, so that's just an extra step. Still, is there a way to simply not have them fetched in the first place?

+2  A: 

Presumably this is happening after you use mysql_fetch_array (or similar).

You need to add in a flag to specify what array type you want returned or PHP assumes both.

i.e. mysql_fetch_array($result_set, MYSQL_ASSOC|MYSQL_NUM|MYSQL_BOTH)

Mike
+1  A: 

That depends on the function you are using. Some functions return both types, others return only one of them.

If you are using PDOStatement->fetch, notice the optional $fetch_style argument it takes.

luiscubal
Thanks! That's what I was looking for.
Ben Saufley
+1  A: 

Your issue is with the mysql_fetch_array function.

If you want only the numbers, use:

$row = mysql_fetch_array($result, MYSQL_NUM)

If you want only the text indexes, use:

$row = mysql_fetch_array($result, MYSQL_ASSOC)

I usually use MySQLi but for PDO you can find more information here: http://us3.php.net/manual/en/pdostatement.fetch.php

Which seems to mean that you should be using this for text indexes:

$row = $statement->fetch(PDO::FETCH_ASSOC);

And this for numeric indexes:

$row = $statement->fetch(PDO::FETCH_NUM);
Kristoffer S Hansen
Thank you! You all told me exactly what I needed to know. In fact, I had been reading an intro to PDO and it mentioned FETCH_ASSOC, but I couldn't find any definitive reference on that term. It was under the link you and luiscubal posted.
Ben Saufley
A: 

Also, just to note this since it isn't listed here, if you want an associative array, you can use mysql_fetch_assoc(), or if you want an enumerated (numbered) array use mysql_fetch_row() instead of mysql_fetch_array(). I use this mostly because without it I would often forget the flag, so I got into the habit of just using the specific function.

Wige