View Full Version : how to retreive real column name in PDO

04-01-2013, 10:58 AM
I need to convert my scripts to using PDO instead of mysql, and have a lot
of queries like the one below.

$connect = new PDO($dsn, $dbUser, $dbPass, $opt);
$query=$connect->prepare("select id, created as Angelegt,has_att ,info as 'Information',
url as Link , validfrom as 'Gültig ab' ,validto as 'Gültig bis' from info order by :order");
$query->execute(Array('order'=>' id desc'));
foreach ($query as $row)
foreach($row as $field=>$value){
echo $field,'--', $value, '<br>';

The output is ok, however my problem is that I need the maping between
the real field name as shown in a show columns from $table and the text
following the AS like in as Angelegt.

What i could need is something like

Gültig ab=>validform,
Gültig bis=>validto

What I get is:

Information--Erster Entwurf zum ausprobieren
Gültig ab--2012-02-14
Gültig bis--2013-01-01

Any Ideas ?

04-01-2013, 06:24 PM
From what I can see in the API, PDO provides no method in which to retrieve the original column name. Fetching the meta on it only provides the aliased name in the result. You'll need to separate the fields into a k => v hashtable pair in order to retrieve that and build your query from it.

MySQLi on the other hand does provide a method in which to do this:

$mysqli = new Mysqli('host', 'name', 'pass');
$stmt = $mysqli->prepare($sQry);
$stmt->bind_param('s', $orderby);
$meta = $stmt->result_metadata();
while ($col = $meta->fetch_field())
printf("%s => %s" . PHP_EOL, $col->name, $col->orgname);

Also, the order by you have is useless. It cannot be used in prepared statements as order by is typically a structural type, and prepared statements are data handlers. So that is treating order by as a literal string "id asc" for which it does order by that, but carries no meaning in the context of a database since 'id' will never be treated as a property and therefore defaults back to database natural ordering (which is, no guaranteed order).