Peter
Peter

Reputation: 407

PDO retrieves two-dimensional array instead of one-dimensional array

In MySQL I have the following table:

|type_id | type_name     |
--------------------------
|1       | John Doe      |
|2       | Peter Griffin |
|3       | Max Wilcox    |

My PHP Code looks like this:

    $stmt = $dbh->prepare ( "SELECT $column FROM $table" );
    $stmt->execute ();

    return $stmt->fetchAll ( PDO::FETCH_ASSOC );

This is the result of the return statement:

Array
(
    [0] => Array
        (
            [type_name] => John Doe
        )

    [1] => Array
        (
            [type_name] => Peter Griffin
        )

    [2] => Array
        (
            [type_name] => Max Wilcox
        )
)

Is there a way to get the following output in a direct way?

Array
(
    [0] => John Doe
    [1] => Peter Griffin
    [2] => Max Wilcox
)

At the moment I am converting a two-dimensional array into a one-dimensional array, but this is quite inefficient. If I use PDO::FETCH_NUM the result looks quite similar but instead of "type_name" I always get "0". Maybe someone can help me to modify my PHP statement? Thanks in advance.

Upvotes: 1

Views: 1941

Answers (1)

Your Common Sense
Your Common Sense

Reputation: 157828

PDO retrieves exactly what you ask it for.

To get a one-dimensional array you have to use PDO::FETCH_COLUMN instead of PDO::FETCH_ASSOC

return $dbh->query("SELECT $column FROM $table" )->fetchAll(PDO::FETCH_COLUMN);

Note that your query is critically prone to SQL injection. PDO shouldn't be used that way. Do not try to automate SQL. It's already perfectly automated. Use a literal query like SELECT foo,bar FROM baz WHERE id=1 instead. There is not that much writing you're probably afraid of, and there will be not that much use of this function in a real world code as you probably hope for.

OR

use a ready-made query builder, such as Doctrine.

Upvotes: 2

Related Questions