PDO在一个查询中使用2个数据库连接

时间:2013-07-02 20:07:55

标签: php sql pdo

我有两个不同的数据库(我可以访问它们),并且它们有一个具有相同结构的表。这是一张名为events的表格。我想连接到两个数据库并从events获取结果,以便我可以显示日期是否大于或等于今天。

$db1 = new PDO('mysql:host='.$db_host1.';dbname='.$db_name1,$db_username1,$db_pass1);
$db2 = new PDO('mysql:host='.$db_host2.';dbname='.$db_name2,$db_username2,$db_pass2);

$db1->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_WARNING);
$db2->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_WARNING);

$today = date("Y-m-d");
$stmt1 = $db1->query("SELECT * FROM events WHERE event_start >= $today ORDER BY event_start ASC");
$stmt2 = $db2->query("SELECT * FROM events WHERE event_start >= $today ORDER BY event_start ASC");

//this works for only one of the database. in this case $stmt1 which connects to db1
while($row = $stmt1->fetch()) { 
//echo'd data will go here  
}

2 个答案:

答案 0 :(得分:6)

在这里尝试做的最好的方法是创建第三个数组来合并结果,然后使用它。像这样:

$db1 = new PDO('mysql:host='.$db_host1.';dbname='.$db_name1,$db_username1,$db_pass1);
$db2 = new PDO('mysql:host='.$db_host2.';dbname='.$db_name2,$db_username2,$db_pass2);

$db1->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_WARNING);
$db2->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_WARNING);

$today = date("Y-m-d");
$query = "SELECT * FROM events WHERE event_start >= $today ORDER BY events ASC";
$stmt1 = $db1->query($query);
$stmt2 = $db2->query($query);

$results = array_merge($stmt1->fetchAll(PDO::FETCH_ASSOC), $stmt2->fetchAll(PDO::FETCH_ASSOC));

// Then sort the new array, perhaps something like this
$events = array();
foreach ($results as $key => $row){
    $events[$key] = $row['events'];
}

array_multisort($key, SORT_ASC, $results);

print_r($results);

我不确定你在活动领域的订购情况;但是,按照相同的标准订购新的$ results数组应该相对容易。查看PHP Array Sorting以获取适当的排序算法。

答案 1 :(得分:-1)

你可能想做一些准备好的陈述。但是,您可以在查询后根据需要合并结果。示例(未经测试)如下:

$stmt1 = $db1->query("SELECT * FROM events WHERE event_start >= :today ORDER BY events ASC");
$stmt2 = $db2->query("SELECT * FROM events WHERE event_start >= $today ORDER BY events ASC");
$combined = array_merge($stmt1->fetchAll(PDO::FETCH_ASSOC), $stmt2->fetchAll(PDO::FETCH_ASSOC));

ksort($combined); // or some other ordering, maybe on date key?

foreach($combined as $record) {
  // use $record['column'] access
}