1

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.

3
  • Is your PHP code in a function ? ref: return $stmt->fetchAll ( PDO::FETCH_ASSOC ); Commented Aug 20, 2015 at 9:35
  • yes it is in a function. Commented Aug 20, 2015 at 9:38
  • @Peter what is name of function? Commented Aug 20, 2015 at 9:38

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the answer. It works now. I know that it is critically prone to SQL injection. Do you have an sugesstion how to improve it?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.