如何设置 php where 语句 array()


How to set up php where statement array()

我想使用 php 通过在数组中存储详细信息来设置动态 WHERE 子句。但是我想有一个默认的 WHERE 它必须检查SchoolId = ? ,无论选择哪个选项。我的问题是我在哪里存储默认的 WHERE SchoolId = ? 最好将其直接放在$query中或放在$where数组中?

$query ='选择...从...';

// 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

我个人的偏好是将默认值放在$where数组中。这样,如果您需要调试或跟踪值,您可以完整地查看放入数组的内容。

至于在何处绑定参数,您需要在准备查询后执行此操作,因此在构造查询后需要第二组 if 语句。

// Initially empty
$where = array('SchoolId = ?');
$parameters = array($schoolID);
$parameterTypes = 'i';
// Check whether a specific student was selected
if($stu !== 'All') {
    $where[] = 'stu = ?';
    $parameters[] = $stu;
    $parameterTypes .= 'i';
}
// Check whether a specific question was selected
// NB: This is not an else if!
if($ques !== 'All') {
    $where[] = 'ques = ?';
    $parameters[] = $ques;
    $parameterTypes .= 'i';
}
// 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);
    $selectedstudentanswerstmt=$mysqli->prepare($query);
    // You only need to call bind_param once
    $selectedstudentanswerstmt->bind_param($parameterTypes,implode($parameters));
}