sergius
sergius

Reputation: 165

How to get an array indexed by column name?

I have this:

$pdo = new PDO("mysql:host=$host;dbname=$databaseName;charset=utf8", $user, $pass);
$query = "SELECT name FROM $tableName";
$stm = $pdo->prepare($query);
$stm->execute();
$array = $stm->fetchAll();
$firephp->log($array);
echo json_encode($array);

Result on ajax is:

[{"name":"mike","0":"mike"},{"name":"john","0":"john"},{"name":"tito","0":"tito"}]

But i want to get this:

{"name":[{"mike","john","tito"}]}

Which PDO fetch_style or what should i do in PHP to receive the string i want on jQuery?

Many thanks.

Upvotes: 0

Views: 152

Answers (2)

Your Common Sense
Your Common Sense

Reputation: 157839

$array = $stm->fetchAll(PDO::FETCH_COLUMN, 0);
echo json_encode(array('name' => $array));

Upvotes: 1

Barmar
Barmar

Reputation: 780818

You can get the column names using PDO:

$col_count = $stmt->columnCount();
$col_names = array();
for ($col = 0; $col < $col_count; $col++) {
    $col_names[] = $stmt->getColumnMeta($col)['name'];
}

Upvotes: 0

Related Questions