I am having trouble with the LIKE statement in my query in MYSQLI. It seems like it is not finding any terms that would go into the LIKE statement. I am trying to bind the parameters into the LIKE statement but my question is that am I setting up the LIKE statement in mysqli incorrectly?
The strange thing is that if I output the query and insert it into SQL, and just change the ‘?’ to a term such as ‘%AAB%’, it works fine in SQL as the it does display the records consisting the term AAB. The problem is that it is not working in PHP,mysqli as that it is not showing any records at all if I type in AAB in the textbox. It keeps stating “Sorry, No Question were found from the Search”.
Does anybody know why this is?
Below is the code (I have connected to db using mysqli):
<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;
}
?>
It looks like mysqli is escaping your
%characters, or something equivalent is happening as part of the client/server communication. Try this:You do realize your
ORDER BYclause is doing absolutely nothing useful, right?