在pdo中多次分配相同的参数值 [英] Assigning the same parameter value multiple times in pdo execute

查看:74
本文介绍了在pdo中多次分配相同的参数值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最初有一条SQL语句,

I originally had an SQL statement, this:

SELECT *, COUNT(friend_one) AS pending_count , COUNT(friend_two) AS requests_sent   
FROM friends
WHERE friend_one OR friend_two = ?
AND status = ?

我在其中分配了像这样的参数:

In which I assigned my parameters like :

$pending_friend_count_stmt->execute(array($user_id, $status_one));

但是,查询没有得到我想要的结果.有人向我展示了另一种方法,但是它多次包含变量$user_id,因此我不知道如何调整代码以使用参数.

However, the query was not getting the results I wanted. Someone showed me a different way of doing it, but it has the variable $user_id in it multiple times, so I do not know how to adjust the code to be able to use a parameter.

您可以在此处查看新查询:

You can see the new query here:

http://rextester.com/KSM73595

我能做到吗

SELECT COUNT(CASE WHEN `friend_one` = ? THEN 1 END) as `requests_count`,
       COUNT(CASE WHEN `friend_two` = ? THEN 1 END) as `pending_count`
FROM `friends`
WHERE ? IN ( `friend_one` , `friend_two` )
  AND `status` = ?

$pending_friend_count_stmt->execute(array($user_id, $user_id, $user_id $status_one));

推荐答案

使用PDO,您可以使用命名参数,但是在您的问题中,您希望对多个值使用1个参数,这意味着必须启用仿真:

Using PDO you have the ability to use named parameters, however in your question you want to use 1 parameters for multiple values and that means emulation has to be on:

$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);

现在您可以执行以下操作:

Now you can do the following:

$stmt = $db->prepare("SELECT * FROM table WHERE userid = :userid AND userid = :userid");

$stmt->excecute([
  ':userid' => 1
]);

结果:

"SELECT * FROM table WHERE userid = 1 AND userid = 1"

这篇关于在pdo中多次分配相同的参数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆