我想使用 php 通过将详细信息存储在数组中来设置动态 WHERE 子句。但我希望有一个默认的 WHERE ,SchoolId = ?
无论选择哪个选项,它都必须检查。我的问题是我在哪里存储默认的SchoolId = ?
最佳位置以便将其直接放入$query
或放入$where
数组中?
$query = 'SELECT ... FROM ...';
// Initially empty
$where = array();
$parameters = array();
// Check whether a specific student was selected
if($stu !== 'All') {
$where[] = 'stu = ?';
$parameters[] = $stu;
}
// Check whether a specific question was selected
// NB: This is not an else if!
if($ques !== 'All') {
$where[] = 'ques = ?';
$parameters[] = $ques;
}
// If we added to $where in any of the conditionals, we need a WHERE clause in
// our query
if(!empty($where)) {
$query .= ' WHERE ' . implode(' AND ', $where);
}
还要设置bind_param()
,包含这个的正确设置是什么?我需要在上面的 if 语句中设置它们还是包含单独的 if 语句?
以下是绑定参数:
$selectedstudentanswerstmt=$mysqli->prepare($selectedstudentanswerqry);
// You only need to call bind_param once
$selectedstudentanswerstmt->bind_param("iii",$_POST["school"],$_POST["student"],$_POST["question"]);
//$_POST["school"] -- SchoolId parameters
//$_POST["student"] -- StudentId parameters
//$_POST["question"] -- QuestionId parameters