我试图从使用多个关键字的表中获取结果。 它适用于单个关键字和两个关键字,但当我尝试查找超过2个关键字时,它不起作用。 看看代码。
if (isset($_POST['keyword'])) {
$keyword = $_POST['keyword'];
// get rid of short words and spaces
$keyword = trim( preg_replace("/[^a-z0-9']+([a-z0-9']{1,3}[^a-z0-9']+)*/i"," "," $keyword ") );
$keyword = trim($keyword, ' ');
// convert phrase to an array of keywords
$keyword = explode(' ', $keyword);
$query = $conn->query("SELECT title, url FROM pages WHERE keywords LIKE '%{$keyword[0]}%'");
if (isset($keyword[1])) {
//$query = $conn->query("SELECT title, url FROM pages WHERE keywords LIKE '%{$keyword[0]}%' OR '%{$keyword[1]}%'");
$query = $conn->query("SELECT title, url FROM pages WHERE keywords LIKE '%{$keyword[0]}%' OR keywords LIKE '%{$keyword[1]}%'");
}
// why is it not reading the third keyword? is it a speed issue?
if (isset($keyword[2])) {
$query = $conn->query("SELECT title, url FROM pages WHERE keywords LIKE IN('%{$keyword[0]}%','%{$keyword[1]}%','%{$keyword[2]}%')");
}
if (isset($keyword[3])) {
$query = $conn->query("SELECT title, url FROM pages WHERE keywords IN('%{$keyword[0]}%','%{$keyword[1]}%','%{$keyword[2]}%','%{$keyword[3]}%')");
}
if (isset($keyword[4])) {
$query = $conn->query("SELECT title, url FROM pages WHERE keywords IN('%{$keyword[0]}%','%{$keyword[1]}%','%{$keyword[2]}%','%{$keyword[3]}%','%{$keyword[4]}%')");
}
我还希望它不能搜索像a,x等单个字符。
答案 0 :(得分:0)
IN
只是对列表中的所有元素进行完全相等的测试,它不像LIKE
那样进行模式匹配。您需要将所有LIKE
测试与OR
结合使用。您可以动态执行此操作,而不是使用所有isset
次调用。
$likes = implode(' OR ', array_map(function($keyword) use ($conn) {
$keyword = $conn->real_escape_string($keyword); // Prevent SQL injection
return "keywords LIKE '%$keyword%'";
}, $keywords));
$sql = "SELECT title, url FROM pages WHERE $likes";
echo "Query to execute: $sql";
$query = $conn->query($sql);
答案 1 :(得分:0)
您可以将字符串分解为单个单词。下面的代码在每个空格后分割字符串。希望这有帮助
$parts = explode(' ', $string);
foreach ($parts as &$query)
$sql =mysql_query("SELECT * FROM search_tbl where keywords like '%$query%'", $conn);
答案 2 :(得分:0)
aar