我在 MYSQLI 的查询中遇到了 LIKE 语句的问题。似乎没有找到任何可以进入 LIKE 语句的术语。我正在尝试将参数绑定到 LIKE 语句中,但我的问题是我是否在 mysqli 中错误地设置了 LIKE 语句?
奇怪的是,如果我输出查询并将其插入 SQL,只需更改“?” 对于诸如“%AAB%”之类的术语,它在 SQL 中运行良好,因为它确实显示了包含术语 AAB 的记录。问题是它在 PHP、mysqli 中不起作用,因为如果我在文本框中输入 AAB,它根本不会显示任何记录。它一直说“对不起,没有从搜索中找到问题”。有人知道这是为什么吗?
下面是代码(我已经使用 mysqli 连接到 db):
<form action="previousquestions.php" method="get">
<p>Search: <input type="text" name="questioncontent" value="<?php echo isset($_GET['questioncontent']) ? $_GET['questioncontent'] : ''; ?>" onchange="return trim(this)" /></p>
<p><input id="searchquestion" name="searchQuestion" type="submit" value="Search" /></p>
</form>
<?php
if (isset($_GET['searchQuestion'])) {
$searchquestion = $_GET['questioncontent'];
$terms = explode(" ", $searchquestion);
$questionquery = "SELECT q.QuestionContent FROM Question q WHERE ";
$i=0;
$whereArray = array();
$orderByArray = array();
$orderBySQL = "";
$paramString = "";
//loop through each term
foreach ($terms as $each) {
$i++;
$whereArray[] = $each;
$orderByArray[] = $each;
$paramString .= 'ss';
//if only 1 term entered then perform this LIKE statement
if ($i == 1){
$questionquery .= "q.QuestionContent LIKE CONCAT('%', ?, '%') ";
} else {
//If more than 1 term then add an OR statement
$questionquery .= "OR q.QuestionContent LIKE CONCAT('%', ?, '%') ";
$orderBySQL .= ",";
}
$orderBySQL .= "IF(q.QuestionContent LIKE CONCAT('%', ?, '%') ,1,0)";
}
$questionquery .= "GROUP BY q.QuestionId, q.SessionId ORDER BY " . $orderBySQL;
$questionquery .= " DESC ";
$stmt=$mysqli->prepare($questionquery)or die($mysqli->error);
function makeValuesReferenced(&$arr){
$refs = array();
foreach($arr as $key => $value)
$refs[$key] = &$arr[$key];
return $refs;
}
$ref = array_merge((array)$paramString, $whereArray, $orderByArray);
call_user_func_array(array($stmt, 'bind_param'), makeValuesReferenced($ref));
$stmt->execute();
$stmt->bind_result($dbQuestionContent);
$questionnum = $stmt->num_rows();
if($questionnum ==0){
echo "<p>Sorry, No Questions were found from this Search</p>";
}
else{
$output = "";
while ($stmt->fetch()) {
$output .= "
<tr>
<td class='questiontd'>$dbQuestionContent</td>
</tr>";
}
$output .= " </table>";
echo $output;
}
?>