我进行了搜索,但找不到任何令人满意的东西
想象以下情况:
<?php
$connection = new \PDO($dsn, $user, $pass);
$stmt1 = $connection->prepare("
SELECT
*
FROM
table
WHERE
a = :a
AND b = :b
AND c = :c
AND d = :d
AND search LIKE :search
");
$stmt1->bindValue(":a", $a);
$stmt1->bindValue(":b", $b);
$stmt1->bindValue(":c", $c);
$stmt1->bindValue(":d", $d);
$stmt2 = clone $stmt1;
$stmt1->bindValue(":search", "a%");
$stmt2->bindValue(":search", "b%");
$stmt1->execute();
$stmt2->execute();
while(($r1 = $stmt1->fetchObject()) && ($r2 = $stmt2->fetchObject()))
echo $r1->foo . " " . $r2->foo . "\n";
}
我可以做这样的事情吗?如何
clone
/重用PDOStatement
实例并在其原始实例的同时使用它?不要说“use
UNION
”,这不是我的问题的重点:P先感谢您。
最佳答案
这不是准备好的语句重用的目的。重用准备好的语句的想法是连续的,而不是并发的。
因此,您可以执行以下操作:
$connection = new \PDO($dsn, $user, $pass);
$stmt = $connection->prepare("
SELECT *
FROM table
WHERE a = :a
AND b = :b
AND c = :c
AND d = :d
AND search LIKE :search
");
$stmt->bindValue(":a", $a);
$stmt->bindValue(":b", $b);
$stmt->bindValue(":c", $c);
$stmt->bindValue(":d", $d);
foreach (["a%", "b%"] as $search) {
$stmt->bindValue(":search", $search);
$stmt->execute();
while($r = $stmt->fetchObject()) {
echo $r->foo . "\n";
}
$stmt->closeCursor();
}
如果要同时处理多个结果集(至少使用MySQL),则需要执行以下操作之一:
UNION
/JOIN
组来创建单个结果集。 如果要使用多个连接,您的代码将变为:
$query = "
SELECT *
FROM table
WHERE a = :a
AND b = :b
AND c = :c
AND d = :d
AND search LIKE :search
";
$connection1 = new \PDO($dsn, $user, $pass);
$connection2 = new \PDO($dsn, $user, $pass);
$stmt1 = $connection1->prepare($query);
$stmt1->bindValue(":a", $a);
$stmt1->bindValue(":b", $b);
$stmt1->bindValue(":c", $c);
$stmt1->bindValue(":d", $d);
$stmt1->bindValue(":search", "a%");
$stmt2 = $connection2->prepare($query);
$stmt2->bindValue(":a", $a);
$stmt2->bindValue(":b", $b);
$stmt2->bindValue(":c", $c);
$stmt2->bindValue(":d", $d);
$stmt2->bindValue(":search", "b%");
$stmt1->execute();
$stmt2->execute();
while(($r1 = $stmt1->fetchObject()) && ($r2 = $stmt2->fetchObject()))
echo $r1->foo . " " . $r2->foo . "\n";
}
$stmt1->closeCursor();
$stmt2->closeCursor();
关于php - 如何重用PDOStatement准备?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21305224/