fetch SQL-join-statement without alias in PHP

拜拜、爱过 提交于 2020-04-18 05:47:37

问题


Following my code:

$list = $pdo->prepare("SELECT * FROM table_a INNER JOIN table_b ON table_a.id = table_b.blabla_id");
$list_result = $list->execute();
while($element = $list->fetch()) {
    //CONTENT
}

Now I would like to fetch the columns with something like echo $element['table_a.id']; - which doesn't work. I don't want to write an alias for every single column. Is there a way to deal with this? :)

SOLUTION:

$list = $pdo->prepare("SELECT * FROM table_a INNER JOIN table_b ON table_a.id = table_b.blabla_id");
$list->execute();
while($element = $list->fetch(PDO::FETCH_ASSOC)) {
    $a = [];
    $i = 0;
    foreach ( $element as $k => $v ) {
        $meta = $list->getColumnMeta($i);
        $a[ $meta['table'] . '.' . $k ] = $v;
        $i++;
    }
    echo $a['table_b.blabla'];
}

As kmoser mentioned, it's possible to improve the effectivity, as it's not necessary to check the column-names every loop, as they don't change.

Thanks to everyone.


回答1:


Once you've fixed your call to $list->fetch() by changing it to $list_result->fetch(), you can use $list_result->getColumnMeta($i) to get meta information (including the table name) of the column in position $i, where $i is the 0-indexed column in the result set.

You can then loop through the columns, retrieve their table names, and populate a new array with updated keys, and values from your original array:

while($element = $list->fetch()) {
    $a = []; // New array
    $i = 0;
    foreach ( $element as $k => $v ) { // For each element in the fetched row
        $meta = $list_result->getColumnMeta($i); // Get the meta info for column $i
        $a[ $meta->table . '.' . $k ] = $v; // E.g. $a[ 'table_a.id' ] = 'Foo'
        $i++; // Point to next column
    }
    $element = $a; // If you really need this variable name
}

Now you can use $element[ 'table_a.id' ].

You'll probably want to make my example more efficient by only looping through the meta info once, since the table names for each column will not change from row to row.

See https://www.php.net/manual/en/pdostatement.getcolumnmeta.php for more information.



来源:https://stackoverflow.com/questions/61195861/fetch-sql-join-statement-without-alias-in-php

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