Nick Shears
Nick Shears

Reputation: 1133

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] => [email protected]
        [2] => [email protected]

    )

)

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?

Upvotes: 2

Views: 1345

Answers (2)

glasz
glasz

Reputation: 2565

this is configurable behavior:

$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.

Upvotes: 6

scrowler
scrowler

Reputation: 24435

If you have a look at the manual, you'll see that fetchAll defaults to returning both an associate index and a numeric index - I'd suggest you use fetch instead and set associate return.

Upvotes: 2

Related Questions