0

詳細を配列に格納することにより、php を使用して動的な WHERE 句を設定したいと考えています。SchoolId = ?しかし、どのオプションが選択されていても、チェックする必要があるデフォルトの WHERE が必要です。私の質問は、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
4

1 に答える 1

1

私の個人的な好みは、デフォルトを $where 配列に入れることです。そうすれば、値をデバッグまたは追跡する必要がある場合に、配列に何が入れられているかを完全に把握できます。

パラメーターをバインドする場所に関しては、クエリを準備した後に行う必要があるため、クエリの作成後に 2 番目の 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 に答える