Php 与PDO/Mysql同时连接时出现问题

Php 与PDO/Mysql同时连接时出现问题,php,mysql,pdo,Php,Mysql,Pdo,以下是我的简化代码: $connexion = new PDO(SQL_DSN,SQL_USERNAME,SQL_PASSWORD); $connexion2 = new PDO(SQL_DSN2,SQL_USERNAME2,SQL_PASSWORD2); [...] $sqlIndex = "SELECT index_key,index_platforms_code FROM index WHERE index_missions_i

以下是我的简化代码:

$connexion = new PDO(SQL_DSN,SQL_USERNAME,SQL_PASSWORD);
$connexion2 = new PDO(SQL_DSN2,SQL_USERNAME2,SQL_PASSWORD2);

[...]

$sqlIndex = "SELECT index_key,index_platforms_code
             FROM   index
             WHERE  index_missions_id = :mission";
$initFiches = $connexion->prepare($sqlIndex);
$initFiches->bindParam(":mission" , $_GET['mission']);
$initFiches->execute();
try 
{
    while ($fiche = $initFiches->fetch(PDO::FETCH_ASSOC))
    {
        print_r($fiche);

        foreach ($structure['champs'] as $masterChamp)
        {
            //$stmt = $connexion2->prepare($masterChamp['sql']);
        }
    }
}
    catch (exception $e)
    {
        echo "error".$e->getMessage();

    }
我的输出:

Array
(
    [index_key] => 1
    [index_platforms_code] => 1
)
Array
(
    [index_key] => 2
    [index_platforms_code] => 2
)
Array
(
    [index_key] => 3
    [index_platforms_code] => 3
)
Array
(
    [index_key] => 4
    [index_platforms_code] => 4
)
好吧,但如果我取消这行的注释

$stmt = $connexion2->prepare($masterChamp['sql']);
在foreach中,这一行打断了上面的while,这是新的输出:

Array
(
    [index_key] => 1
    [index_platforms_code] => 1
)

有人有主意吗?

这里有一个解决方案,它不需要2个连接,而且更优化

$connexion = new PDO(SQL_DSN,SQL_USERNAME,SQL_PASSWORD);
$sqlIndex = "SELECT index_key,index_platforms_code
             FROM   index
             WHERE  index_missions_id = :mission";

$initFiches = $connexion->prepare($sqlIndex);

$initFiches->bindParam(":mission" , $_GET['mission'], PDO::PARAM_STR);

$initFiches->execute();

$data = $stmt->fetchAll(PDO::FETCH_ASSOC);

$stmt = $connexion->prepare("SELECT ...."); // Prepare outside of the loop, you don't have to prepare it X times, once is enough.

if(sizeof($data))
{
    foreach($data as $row)
    {
        // Do your statement binding / executing.    
    }
}

或者,您似乎可以通过表连接来实现这一点,而不是对从第一个表获得的每一行发出查询。由于您还没有发布结构,我想目前对它没有多大帮助。

谢谢您的回答,但我使用了两个连接,因为它实际上是两个mtsql数据库,在两个不同的服务器上……即使有两个不同的数据库,您也不应该在循环内编写语句,而是在循环外编写。为了了解实际发生的情况,将PDO设置为异常模式,并使用try/catch块捕获任何发生的异常。您的代码并没有真正显示发生错误时会发生什么。哦,我需要说的是,在我的实际代码中,我准备的查询存储在“structure['champs']数组中,每个结构['champs']都有不同的查询。。那么我如何才能退出prepare?在这种情况下,你不能,但那是一个完全不同的场景,因为它与你描述的初始问题没有相似之处:)不应该真的导致问题(我也一直这样做,因为同样的原因不同的物理数据库),应该可以工作。您确定已创建这两个连接吗?你真的得到了一个特定的错误吗?尝试用try-catch包装以获取任何错误…try-catch不显示任何错误。。。连接都正常,我通过显示查询结果验证了这一点