如何在同一个foreach循环中加入两个PDO对象? [英] How do you join two PDO objects in the same foreach loop?

查看:139
本文介绍了如何在同一个foreach循环中加入两个PDO对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请原谅我,因为我是PDO的新手.我不确定是否有一个简单的解决方案.我已经在网上搜索了一段时间,但尚未找到答案.

Forgive me because I'm new to PDO. I'm not sure if there is a simple solution. I've been searching online for some time and have yet to find an answer.

我要连接到两个不同的数据库.

I have two different databases that I'm connecting to.

try {
    $db1= new PDO( "sqlsrv:server=$server;Database = $dbname", $uid, $pwd); 
    $db2= new PDO( "sqlsrv:server=$server;Database = $db2name", $db2uid, $pwd); 
}

我正在尝试基于公共ID将每个数据库中的表中的信息进行联接.我需要遍历信息以打印列表.

I'm trying to join information from a table on each database based on a common ID. I need to loop through the information to print a list.

$sql= 
    "SELECT tableA.name, tableB.messages 
     FROM tableA INNER JOIN tableB ON tableA.id = tableB.id";

foreach ($db1->query($sql) as $row) {
//HOW CAN I QUERY DB2??
    $id = $row['id'];
    $name = $row['name'];
    $msg= $row['messages'];

    echo $name . "etc...";
}

如何修改此代码以查询两个PDO,以便可以在相同的foreach循环中打印出结果?

How can I modify this code to query both PDOs so that it can print out results in the same foreach loop?

我试图将tableA中的ID与tableB中的ID进行匹配,然后在ID匹配时在tableB中的msg字段旁边打印tableA中的名称字段.

I am trying to match up an ID in tableA with an ID in tableB and then print the name field in tableA next to the msg field in tableB when the IDs match.

推荐答案

让我们想象一下(因为您没有向我们提供数据库模式),您的表具有db1

Let's imagine (since you don't provide us your DB schema) that you have db1 with table

Db1table
    id_1
    name_1
    message_1

和带表的db2

Db2table
   id_2
   name_2
   message_2

每个id_1指的是通用的对应id_2,例如 array('id_1'=>1, 'name_1'=>'smth', 'message_1'=>'smth')必须与array('id_2'=>1, 'name_2'=>'smth', 'message_2'=>'smth')连接(如您所见,id_1 == id_2).

And each id_1 refers to common corresponding id_2, eg array('id_1'=>1, 'name_1'=>'smth', 'message_1'=>'smth') must be joined with array('id_2'=>1, 'name_2'=>'smth', 'message_2'=>'smth') (as you see, id_1==id_2).

因此,您需要的代码是:

So, code you need is:

# make a "indexed" hash by common id column for fast access
$hash_by_id=array();
foreach($db2->query($sql2) as $row2){
    $hash_by_id[$row2['id_2']]=$row2;
}

foreach($db1->query($sql1) as $row1){
    $joined_row2=$hash_by_id[$row1['id_1']]; #pseudo-join
    echo $joined_row2['id_2']==$row1['id_1'] # true
    # from db1
    echo $joined_row2['id_2'];
    echo $joined_row2['name_2'];
    echo $joined_row2['message_2'];
    # from db2
    echo $row1['id_1'];
    echo $row1['name_1'];
    echo $row1['message_1'];
}

这篇关于如何在同一个foreach循环中加入两个PDO对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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