【发布时间】:2012-06-26 11:55:15
【问题描述】:
我不知道我是否正确,但我想做的是用户在文本框中输入一个术语或多个术语,并且在用户提交文本框后,它应该显示包含该术语的任何结果。但我似乎无法让它工作,所以我的问题是,当我使用 mysqli 在文本框中输入时能够从数据库中检索术语时,我是否走在正确的轨道上?我不确定查询是否与 like 语句正确,是否循环遍历每个术语,但如果有人能提供帮助,将不胜感激:)
我也收到了警告,这是需要修复的:
警告:mysqli_stmt::bind_param() [mysqli-stmt.bind-param]: Number of variables does not match number of parameters in Prepared statement in ... on line 84。如何解决?
下面是mysqli部分的代码:
<?php
$username="xxx";
$password="xxx";
$database="mobile_app";
$mysqli = new mysqli("localhost", $username, $password, $database);
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
die();
}
$questioncontent = (isset($_GET['questioncontent'])) ? $_GET['questioncontent'] : '';
?>
<form action="previousquestions.php" method="get">
<p>Search: <input type="text" name="questioncontent" value="<?php echo $questioncontent; ?>" onchange="return trim(this)" /></p>
<p><input id="searchquestion" name="searchQuestion" type="submit" value="Search" /></p>
</form>
<?php
if (isset($_GET['searchQuestion'])) {
$searchquestion = $questioncontent;
$terms = array(explode(" ", $searchquestion));
//loop through each term
foreach ($terms as &$each) {
$each = '%'.$each.'%';
$questionquery = "
SELECT q.QuestionContent
FROM Question q
WHERE ";
$i=0;
$whereArray = array();
$orderByArray = array();
$orderBySQL = "";
$paramString = "";
//loop through each term
foreach ($terms as &$each) {
$each = '%'.$each.'%';
$i++;
//if only 1 term entered then perform this LIKE statement
if ($i == 1){
$questionquery .= "q.QuestionContent LIKE ? ";
} else {
//If more than 1 term then add an OR statement
$questionquery .= "OR q.QuestionContent LIKE ? ";
$orderBySQL .= ",";
}
$orderBySQL .= "IF(q.QuestionContent LIKE ? ,1,0)";
$whereArray = "%" . $each . "%";
$orderByArray = $each;
$paramString = "ss";
}
$questionquery .= "GROUP BY q.QuestionId, q.SessionId ORDER BY " . $orderBySQL;
$stmt=$mysqli->prepare($questionquery)or die($mysqli->error);;
$stmt->bind_param($paramString, array_merge($whereArray, $orderByArray));
$stmt->execute();
$stmt->bind_result($dbQuestionContent);
$questionnum = $stmt->num_rows();
}
?>
【问题讨论】:
-
您是否尝试过回显您的 SQL 查询以查看它的样子?
-
当我回显查询时,它始终显示:
SELECT q.QuestionContent FROM Question q WHERE q.QuestionContent LIKE ? OR q.QuestionContent LIKE ? GROUP BY q.QuestionId, q.SessionId ORDER BY +IF(q.QuestionContent LIKE ? ,1,0) DESC。我认为这不正确,因为假设您只输入 1 个术语,应该是这个SELECT q.QuestionContent FROM Question q WHERE q.QuestionContent LIKE ? GROUP BY q.QuestionId, q.SessionId ORDER BY +IF(q.QuestionContent LIKE ? ,1,0) DESC但是如果你然后输入 3 个术语,例如它应该更改为这个...... -
SELECT q.QuestionContent FROM Question q WHERE q.QuestionContent LIKE ? OR q.QuestionContent LIKE ? OR q.QuestionContent LIKE ? GROUP BY q.QuestionId, q.SessionId ORDER BY +IF(q.QuestionContent LIKE ? ,1,0) DESCOR 语句需要根据文本框中输入的术语数量自行更改 -
那你需要打勾,统计搜索框中输入的词条的个数,多于一个才加上OR语句。
-
此外,您需要为包含的每个绑定参数调用
bindParam- SQL 中的每个?都需要一个;因此您需要确保以正确的顺序传递正确的参数。