phpmysqlpdo

Strange PDO results returning a key for each row value


Trying to get some database results in a very simple application.

Code

$pdo = new PDO("mysql:host=localhost;dbname=soundinsider", "root", "");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM users";
$query = $pdo->query($sql);

echo '<pre>';
print_r($query->fetchAll());

And this is what's output

Array
(
[0] => Array
    (
        [user_id] => 1
        [0] => 1
        [username] => simon
        [1] => simon
        [email] => madeup
        [2] => madeup

    )

[1] => Array
    (
        [user_id] => 2
        [0] => 2
        [username] => bobwin
        [1] => bobwin
        [email] => fake@email.com
        [2] => fake@email.com

    )

)

So there seems to be an extra key created for each result. This wasn't the case when I was coding a month or two ago. Is there something wrong here or is this now PDO behaviour?


Solution

  • This is configurable behaviour:

    $statement->fetchAll(PDO::FETCH_ASSOC)
    

    will return associative arrays -- see argument $fetch_style.

    You can configure your PDO instance to always do this:

    $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
    

    there also is PDOStatement::setFetchMode() which is useful when using repeated prepared statements.