-1

How would you fetch a mysql query with PDO (Or after PDO) in order to have this result? I mean the "titles of the columns" in the first position of the array and the values in the next positions? Can somebody helping me with an example?

[

["ColumnTitle","Column2Title"],
["RecordValue1","RecordValue2"],
["RecordValue1","RecordValue2"],
["RecordValue1","RecordValue2"],
["RecordValue1","RecordValue2"]

]

The mysql query returns:

ColumnTitle  | Column2Title
----------------------------
RecordValue1   RecordValue2
RecordValue1   RecordValue2
RecordValue1   RecordValue2
RecordValue1   RecordValue2

I don't think this question was duplicate, this was a specific case.. :(

notme
  • 451
  • 6
  • 17
  • http://php.net/manual/en/pdostatement.getcolumnmeta.php – Jay Blanchard Aug 13 '15 at 14:40
  • Oh thanks, so then I should use: `$columns=$db->fetchAll(PDO::FETCH_COLUMN);` and then append the data rows into the array with a foreach, right? How would you select just the rows? – notme Aug 13 '15 at 14:58
  • @JayBlanchard it worked with `$result = $db->query($query); for ($i = 0; $i < $result->columnCount(); $i++) { $col = $result->getColumnMeta($i); $columns[] = $col['name']; }` But my second problem remains, how would I get just the values in order to append them into the array? – notme Aug 13 '15 at 15:35

1 Answers1

0

PDO doesn't offer such a format out of the box (because no developer would like it this way), but you can make it with minor tweaking

$data = $pdo->query('SELECT * FROM users')->fetchAll(PDO::FETCH_ASSOC);
array_unshift($data, array_keys($data));

But in your place I wouldn't add column names to the data array at all.

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
  • Thanks for your suggestion, unfortunatly it doesn't really do what it's expected.. :( I need something that puts in the first positions of the array just the columns name and in the next ones the values. BTW I've fixed the question by precising that also just PHP would help. ;) – notme Aug 13 '15 at 15:20