我在我的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;
}
?>
這是什麼意思:'LIKE?' –
@MattK:'?'是一個mysqli佔位符,用於使用'bind_param'綁定參數。 – chaos
啊,集成電路。學到了新東西! –