PDOStatement::fetch() 和重复的字段名称 [英] PDOStatement::fetch() and duplicate field names

查看:53
本文介绍了PDOStatement::fetch() 和重复的字段名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个使用 MySQL 和 PHP 5.3.8 的网络应用程序.我们有一种机制可以将简化的查询指令转换为完整的查询字符串,包括连接.

I'm working on a web application using MySQL and PHP 5.3.8. We have a mechanism to translate a simplified query instruction into a complete query string, including joins.

由于我不知道将连接哪些(标准化)表以及它们的字段称为什么,因此可能存在重复的字段名称.当执行 PDOStatement::fetch(PDO::FETCH_ASSOC) 时,我得到一个关联的字段名称数组:

Since I cannot know what (normalized) tables there will be joined and what their fields are called, there may be duplicate field names. When executing PDOStatement::fetch(PDO::FETCH_ASSOC), I get an associated array of field names:

$test = $this->DBConnection->prepare("SELECT `events`.`Title`, `persons`.`Title` FROM `events` JOIN `persons` ON `events`.`HostID` = `persons`.`ID`;");
$test->execute();
$test->fetch();

但是我无法区分重复的字段名称,例如title".更糟糕的是,重复项会相互覆盖:

But I have no way of distinguishing repeating field names, such as "title". Worse, duplicates overwrite each other:

array('Title' => 'Frodo Baggins');

在过去的糟糕日子里,我在每个字段上运行 mysql_fetch_field() 来获取每个字段的表.请告诉我,有比给字段添加前缀更好的方法 (SELECT events.Title AS eventsTitle;).

In the bad old days, I ran mysql_fetch_field() on each field to get the table for each field. Please, tell me there is a better way than prefixing the fields (SELECT events.Title AS eventsTitle;).

非常感谢您的帮助!

推荐答案

在查询中为它们指定别名,这样它们就不会重复:

Give them aliases in the query so they won't be duplicates:

SELECT events.Title AS eTitle, persons.Title AS pTitle FROM ...

那么该行将是:

array('eTitle' => 'Hobbit Meeting', 'pTitle' => 'Frodo Baggins');

另一种方法是将结果作为索引数组而不是关联数组来获取:

The alternative is to fetch the result as an indexed array rather than associative:

$test->fetch(PDO::FETCH_NUM);

然后你会得到:

array('Hobbit Meeting', 'Frodo Baggins');

并且您可以通过 $row[0]$row[1] 访问它们.

and you can access them as $row[0] and $row[1].

这篇关于PDOStatement::fetch() 和重复的字段名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆