gpt4 book ai didi

php - 如何在 PHP PDO 中简单地将一个值绑定(bind)到所有参数?

转载 作者:可可西里 更新时间:2023-10-31 23:00:38 24 4
gpt4 key购买 nike

我有以下函数

function searchusers($username){
$result=$this->conn->prepare("SELECT username,
profilimg,
(SELECT COUNT(title) FROM animelist WHERE mystatus='Watching' AND addedby LIKE CONCAT('%','?','%')) AS watching,
(SELECT COUNT(title) FROM animelist WHERE mystatus='Completed' AND addedby LIKE CONCAT('%','?','%')) AS completed,
(SELECT COUNT(title) FROM animelist WHERE mystatus='On-hold' AND addedby LIKE CONCAT('%','?','%')) AS onhold,
(SELECT COUNT(title) FROM animelist WHERE mystatus='Dropped' AND addedby LIKE CONCAT('%','?','%')) AS dropped,
(SELECT COUNT(title) FROM animelist WHERE mystatus='Plan to watch' AND addedby LIKE CONCAT('%','?','%')) AS plantowatch,
(SELECT COUNT(title) FROM animelist WHERE addedby LIKE CONCAT('%','?','%')) AS all,
(SELECT COUNT(title) FROM animelist WHERE addedby LIKE CONCAT('%','?','%') AND favourite='1') AS favourites,
(SELECT COUNT(subject) FROM comments WHERE name LIKE CONCAT('%','?','%')) AS allcomments,
(SELECT COUNT(review) FROM reviews WHERE addedby LIKE CONCAT('%','?','%')) AS allreviews,
(SELECT AVG(myscore) FROM animelist WHERE addedby LIKE CONCAT('%','?','%')) AS meanscore
FROM user WHERE username LIKE CONCAT('%','?','%') LIMIT 120");
$result->bindparam(1,$username);
$result->bindparam(2,$username);
$result->bindparam(3,$username);
$result->bindparam(4,$username);
$result->bindparam(5,$username);
$result->bindparam(6,$username);
$result->bindparam(7,$username);
$result->bindparam(8,$username);
$result->bindparam(9,$username);
$result->bindparam(10,$username);
$result->bindparam(11,$username);
$result->execute();
return $result->fetchall();
}

如您所见,我将相同的值绑定(bind)到 11 个参数,但我是通过重复 $result->bindparam(1,$username); 11 次来完成的,这看起来很糟糕。

我想问的是,是否有更好的解决方案将一个值绑定(bind)到所有参数,而不是重复多次 bindparam

我可能可以使用命名占位符而不是问号更轻松地解决这个问题,但这不是我现在正在寻找的解决方案。

我认为有一种方法可以通过 for/foreach 来解决这个问题,但我不知道它应该是什么样子。

最佳答案

for($i=0; $i<11; $i++){
$result->bindparam($i,$username);
}
return $result->fetchall();

因为您知道有 11 个绑定(bind)参数,所以您可以简单地使用一个计数器。

关于php - 如何在 PHP PDO 中简单地将一个值绑定(bind)到所有参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56162886/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com