如何设置php where语句数组()

时间:2013-01-27 14:30:54

标签: php mysqli

我想通过在数组中存储细节来使用php来设置动态WHERE子句。但我希望有一个默认的WHERE,它必须检查SchoolId = ?,无论选择哪个选项。我的问题是我在哪里存储SchoolId = ?的默认WHERE最好直接放在$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

1 个答案:

答案 0 :(得分:1)

我个人的偏好是将默认值放在$ where数组中。这样,如果您需要调试或跟踪值,您可以全面了解放入阵列的内容。

至于绑定params的位置,您需要在准备查询后执行此操作,以便在构造查询后需要第二组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));
}