<?$search=$_POST['search'];
$query = $pdo->prepare("select * from tag where tag1 LIKE '%$search%' OR tag2 LIKE '%$search%' LIMIT 0 , 10");
$query->bindValue(1, "%$search%", PDO::PARAM_STR);
$query->execute();
// Display search result
if (!$query->rowCount() == 0) {
echo "Search found :<br/>";
while ($results = $query->fetch()) {
echo "$".$results['name'];
echo "</td></tr>";
}
echo "</table>";
} else {
echo 'Nothing found';
}
?>
<form action="" method="post">
Search: <input type="text" name="search" placeholder=" Search here ... "/>
<input type="submit" value="Submit" />
</form>
我知道有很多类似的问题,但我仍然无法弄清楚。如果有人有时间,请解释我如何将explode
添加到我的搜索中,以便我可以使用多于1个单词进行搜索?
非常感谢你的时间。
如果我在我的case标签中输入1个单词,则此脚本会搜索。但如果我输入2个单词,它将返回0个结果。
答案 0 :(得分:2)
请注意bindValue
上有关第一个参数的文档:
参数标识符。
对于使用命名占位符的预准备语句,这将是
:name
形式的参数名称。对于使用问号占位符的预准备语句,这将是参数的1索引位置。
您的SQL字符串中既没有?
占位符也没有以冒号为前缀的命名占位符。相反,你
实际上直接在SQL中注入用户提供的输入,并且易受SQL注入攻击。
因此,您应该开始使用文档中描述的占位符。
如果您想要找到任何单独的字词,那么您需要扩展WHERE
动态地,添加OR条件以匹配每个单词。使用?
占位符会更容易
在这种动态生成的SQL中。
此外,由于您的参数是字符串,您可以使用execute
的可选参数来传递参数数组:
<强> input_parameters 强>
具有与正在执行的SQL语句中的绑定参数一样多的元素的值数组。所有值都被视为
PDO::PARAM_STR
。
以下是一些建议的代码:
// Explode to words and filter for words which are not the empty string:
$words = array_filter(explode(" ", $_POST['search']), 'strlen');
// Wrap each of the words in '%'
$words = array_map(function ($search) { return "%$search%"; }, $words);
// Add a condition for each of the words in the WHERE clause, and repeat for tag2
$sql = "select *
from tag
where " .
implode(" OR ", array_fill(0, count($words), "tag1 LIKE ?")) .
" OR " .
implode(" OR ", array_fill(0, count($words), "tag2 LIKE ?")) .
" LIMIT 0, 10";
$query = $pdo->prepare($sql);
// Pass the values as string twice: once for tag1 and once for tag2
$query->execute(array_merge($words, $words));