Combine Results from Two PDO queries

倖福魔咒の 提交于 2020-01-05 07:44:28

问题


I have the following line:

$products = $dbh->query("SELECT piP2Components.typeID, invTypes.typeName FROM piP2Components INNER JOIN invTypes ON piP2Components.typeID = invTypes.typeID ORDER BY invTypes.typeName ASC;");

I have another table, piP3Components and I would like to run the same query on it and have the results added to the $products variable. As the result is a PDOStatement object I can't simply array_push.

How would I go about doing this? Alternatively, I'm fairly new to using JOIN queries, is there a way to accomplish this in SQL without having the piP3Components.typeID results in a different column?

Thanks.


回答1:


You have two options.

First, if the columns you're picking from each table have identical column types, you can use a UNION:

SELECT foo, bar, baz FROM something WHERE ...
UNION ALL
SELECT qux AS foo, meta AS bar, syntactic AS baz FROM elsewhere WHERE ...

Second, you can run both queries, then fetch the results for each and place them in a single array, using that array later instead of the statement handle when processing the results:

$results = array();

$sth_a = $pdo->prepare(...);
$sth_a->execute(...);
while($row = $sth_a->fetch(PDO::FETCH_ASSOC))
    $results[] = $row;

$sth_b = $pdo->prepare(...);
$sth_b->execute(...);
while($row = $sth_b->fetch(PDO::FETCH_ASSOC))
    $results[] = $row;

print_r($results);


来源:https://stackoverflow.com/questions/5529824/combine-results-from-two-pdo-queries

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