PDOStatement::fetch() and duplicate field names

对着背影说爱祢 提交于 2021-02-07 20:49:10

问题


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.

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();

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

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

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;).

Your help is greatly appreciated!


回答1:


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

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

Then the row will be:

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);

Then you'll get:

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

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



来源:https://stackoverflow.com/questions/21071353/pdostatementfetch-and-duplicate-field-names

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!