在旧的mysql代码中,我在下面有一个查询,它完美地工作在下面:
$questioncontent = (isset($_GET['questioncontent'])) ? $_GET['questioncontent'] : '';
$searchquestion = $questioncontent;
$terms = explode(" ", $searchquestion);
$questionquery = "
SELECT q.QuestionId, q.QuestionContent, o.OptionType, an.Answer, r.ReplyType,
FROM Answer an
INNER JOIN Question q ON q.AnswerId = an.AnswerId
JOIN Reply r ON q.ReplyId = r.ReplyId
JOIN Option_Table o ON q.OptionId = o.OptionId
WHERE ";
foreach ($terms as $each) {
$i++;
if ($i == 1){
$questionquery .= "q.QuestionContent LIKE `%$each%` ";
} else {
$questionquery .= "OR q.QuestionContent LIKE `%$each%` ";
}
}
$questionquery .= "GROUP BY q.QuestionId, q.SessionId ORDER BY "; $i = 0; foreach ($terms as $each) {
$i++;
if ($i != 1)
$questionquery .= "+";
$questionquery .= "IF(q.QuestionContent LIKE `%$each%` ,1,0)";
}
$questionquery .= " DESC ";
但是因为那个旧的mysql正逐渐消失,人们说要使用PDO或mysqli(因为我目前得到的php版本不能使用PDO),我尝试将我的代码更改为mysqli,但这给了我问题。在下面的代码中我省略了bind_params命令,我的问题是如何在下面的查询中绑定参数?它需要能够绑定多个$each
,因为用户可以输入多个术语,并且每个$each
都被归类为术语。
以下是同一查询的当前mysqli代码:
$questioncontent = (isset($_GET['questioncontent'])) ? $_GET['questioncontent'] : '';
$searchquestion = $questioncontent;
$terms = explode(" ", $searchquestion);
$questionquery = "
SELECT q.QuestionId, q.QuestionContent, o.OptionType, an.Answer, r.ReplyType,
FROM Answer an
INNER JOIN Question q ON q.AnswerId = an.AnswerId
JOIN Reply r ON q.ReplyId = r.ReplyId
JOIN Option_Table o ON q.OptionId = o.OptionId
WHERE ";
foreach ($terms as $each) {
$i++;
if ($i == 1){
$questionquery .= "q.QuestionContent LIKE ? ";
} else {
$questionquery .= "OR q.QuestionContent LIKE ? ";
}
}
$questionquery .= "GROUP BY q.QuestionId, q.SessionId ORDER BY "; $i = 0; foreach ($terms as $each) {
$i++;
if ($i != 1)
$questionquery .= "+";
$questionquery .= "IF(q.QuestionContent LIKE ? ,1,0)";
}
$questionquery .= " DESC ";
$stmt=$mysqli->prepare($questionquery);
$stmt->execute();
$stmt->bind_result($dbQuestionId,$dbQuestionContent,$dbOptionType,$dbAnswer,$dbReplyType);
$questionnum = $stmt->num_rows();
答案 0 :(得分:4)
请参阅此SO Post,其中讨论了call_user_func_array与bind_param()
的使用情况。
从PHP Docs on mysqli_stmt_bind_param开始说明以下内容......
注意:强>
结合使用mysqli_stmt_bind_param()时必须小心 使用call_user_func_array()。请注意mysqli_stmt_bind_param() 要求参数通过引用传递,而 call_user_func_array()可以接受变量列表作为参数 可以代表参考或价值。
你会想要使用这样的东西
call_user_func_array(array($stmt, 'bind_param'), $terms);
并且您可以确保在SQL字符串?
中显示正确数量的$stmt
个字符。
<强> [编辑] 强>
这是一个有效的例子
// user entered search strings
$user_terms = array("a", "b", "c");
// append your wildcard "%" to all elements. you must use "&" reference on &$value
foreach ($user_terms as &$value) {
$value = '%'.$value.'%';
}
$types = "";
for($i = 0; $i<sizeof($user_terms); $i++) {
$types .= "s";
}
$terms = array_merge( array($types), $user_terms);
// the array $terms now contains: { "sss", "%a%", "%b%", "%c%" }
$sql = "SELECT ... ?,?,?" // edit your sql here
$stmt = $mysqli->prepare($sql)
call_user_func_array(array($stmt, 'bind_param'), $terms);