I have a simple table with one field “id”, and when I execute this code…
$dbh = new PDO('mysql:host='.$dbhost.';dbname='.$dbname, $dbuser, $dbpass);
$sql = 'SELECT * FROM logolist';
$q = $dbh->query($sql);
while($r = $q->fetch()){ print_r($r); }
… I get this output:
Array
(
[ID] => 2
[0] => 2
)
Array
(
[ID] => 4
[0] => 4
)
As you see, there’s a [0] under the field “ID”. if I add more field, I keep getting more extra elements inside the array. It’s like every field is outputting it’s value 2 times.
Why is this?
I’m encountering this practice of having a loop for fetching MySQL results and I’m wondering why people do it so I’ll write up this answer and try to clear up a few things.
1) You do not need a loop to fetch results
2) Reason you get the results duplicated is because you’re receiving an associative array and index-based one. That’s the default behaviour.
What you can do is this: