1

I am using the following query:

SELECT foo, bar FROM mytable WHERE foo=:foo AND userid=:userid;

I want to loose the AND userid=:userid part for 'admin' class users (they get to see the foos of all users).

Is there a way to do that using PDO prepared statements? Or am I to use string concatenation to create two different queries? I was thinking of using some kind of LIKE structure also, but it feels a little lumpy.

4

1 回答 1

0

不,你不能这样做。

您可以有两个准备好的语句并使用逻辑在它们之间进行选择。

$queryWithUser = $pdo -> prepare ('SELECT foo, bar FROM mytable WHERE foo=:foo AND userid=:userid;');
$queryWithoutUser = $pdo -> prepare ('SELECT foo, bar FROM mytable WHERE foo=:foo;');

$result = $doQueryWithUser?
    $queryWithUser -> execute (array ('foo' => 123, 'userid' => 456)):
    $queryWithoutUser -> execute (array ('userid' => 456));

或者您可以根据需要在特定时间生成您需要的准备好的语句。

$queryString = 'SELECT foo, bar FROM mytable WHERE foo=:foo';
if ($doQueryWithUser) {
    $queryString .= ' AND userid=:userid';
}
$query = $pdo -> prepare ($queryString . ';');
于 2013-05-15T12:00:17.990 回答