所以我有以下function
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();
}
如您所见,我将相同的值绑定到11个参数,但是通过重复$result->bindparam(1,$username);
11次来做到这一点,这看起来非常糟糕。
我要问的是,是否有更好的解决方案将一个值绑定到所有参数,而不是多次重复bindparam
?
我可以使用命名占位符而不是问号来解决这个问题,但这不是我现在要寻找的解决方案。
我认为有一种方法可以解决for
/ foreach
的问题,但我不知道它的外观。
感谢您的帮助!
答案 0 :(得分:2)
for($i=0; $i<11; $i++){
$result->bindparam($i,$username);
}
return $result->fetchall();
由于您知道有11种绑定参数,因此可以简单地使用计数器。
答案 1 :(得分:2)
虽然其他答案在技术上正确无误,但您需要什么?在您的问题和所提供的代码的上下文中,它不是最佳解决方案,因为使用循环绑定参数通常不是一个好习惯。
相反,我建议您只使用相同的参数并将其绑定一次(或更改您的问题)。
为此,请使用命名参数:使用?
代替:parameterName
然后bindparam('parameterName', $yourVariable)
。 (请参阅官方docs)。
也许您可以扩展问题以使用例更加清楚。在此之前,命名参数是最佳解决方案。