我有一个纤薄的GET方法设置,其基本签名如下所示:
$app->get('/musicians/name/:name', function($name) use ($allFields, $app, $db)
然后我创建了一些查询文本,类似于:
$queryText = "SELECT date, bio, articles FROM Musicians WHERE name = :name"
然后我继续将:name参数绑定到调用函数时引入的$ name变量。
这很好用,但是如果我想让用户一次搜索多个音乐家会怎么样?有没有办法可以让用户在网址中添加一些内容,将$queryText
转换为"SELECT date, bio, articles FROM Musicians WHERE name = 'Beethoven' OR 'Bach' OR 'The Sex Pistols'"?
注意:我正在使用PDO进行数据库处理。
答案 0 :(得分:1)
是的,你可以这样做:
$queryText = "SELECT date, bio, articles
FROM Musicians
WHERE name = :name or name = :name1 or name = name2";
然后,您可以单独绑定每个值或使用值数组绑定。
更新
您可以在网址中使用name1& name2& name3,然后,您可以使用:
<?php
$names = explode("&", $querystring); //$querystring here is name1&name2&name3
//now names is an array contains all keywords
//lets build the query
$i = 1;
foreach($names as $name){
$where[] = "name = :name$i";
$params[":name$i"] = $name;
$i++;
}
$queryText = "SELECT date, bio, articles
FROM Musicians
WHERE ".implode(" OR ", $where);
$sth = $dbh->prepare($queryText);
$sth->execute($params);
?>