0

我想使用 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
4

1 回答 1

1

我个人的偏好是将默认值放在 $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));
}
于 2013-01-27T14:36:34.917 回答