2与PDO / Mysql同时连接的问题

时间:2011-07-08 09:20:17

标签: 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_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中,这一行打破了上面的时间,这是新的输出:

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

有人有想法吗?

1 个答案:

答案 0 :(得分:0)

这是一个不涉及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.    
    }
}

或者,似乎您可以使用表连接执行此操作,而不是为从第1个表中获取的每一行发出查询。由于你还没有发布结构,我想目前没有多少帮助它。