我想使用用户定义的搜索词在表中进行搜索。 我是通过将字符串拆分来构造sql来实现的。
但是我似乎无法使其正常工作。如果只输入一个单词,但是输入两个或多个单词,它会崩溃,效果很好。
$q = $_GET['q']; //Search word
$q = htmlspecialchars($q);
$q_exploded = explode ( " ", $q );
foreach( $q_exploded as $search_each ) {
$where .= "content LIKE ? OR ";
$bind .= "s";
$param .= "%$search_each%, ";
}
$where = rtrim($where,'OR ');
$param = rtrim($param,', ');
$sql = "SELECT ads_id FROM search_index WHERE ".$where."";
echo $sql . "<br>".$param."<br>".$bind."<br>";
$stmt = $dbconn->prepare($sql);
$stmt->bind_param($bind, $param);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
echo $row['ads_id'];
}
这是我的错误
从search_index中选择ads_id,在什么地方喜欢?或内容类似?
%word1%,%word2%
ss
警告:mysqli_stmt :: bind_param():类型中的元素数 定义字符串与绑定变量的数量不匹配
答案 0 :(得分:0)
您的问题在这里:
$stmt->bind_param($bind, $param);
您正在做的是:
$stmt->bind_param("ss", $param);
尽管您可能希望param满足这两个字符串,但您不需要为每个字符串传递一个变量。我会尝试为此爆炸。
答案 1 :(得分:0)
有人早些时候发布了答案,但又将其删除。该答案确实有效,我只需要从mySQLi更改为DPO。
解决方案: $ q = htmlspecialchars($ q); $ q_exploded =爆炸(“”,$ q);
$where = [];
$bind = [];
foreach ($q_exploded as $idx => $search_each) {
$key = ':val' . $idx;
$where[] = "content LIKE " . $key;
$bind[$key] = "%$search_each%";
}
$sql = "SELECT ads_id FROM search_index WHERE " . implode(" OR ", $where);
$stmt = $pdo_conn->prepare($sql);
$stmt->execute($bind);
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
while ($row = $stmt->fetch()) {
echo $row['ads_id'] . "<br>";
}