I want to use php to set dynamic WHERE clause by storing details in an array. But I want to have a default WHERE where it has to check for SchoolId = ?, no matter which option is chosen. My question is where do I store the default WHERE for SchoolId = ? Best to put it straight in the $query or put it in the $where array?
$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);
}
Also to set up the bind_param(), what is the correct set up to include this? Do I need to set them up in the if statements above or include seperate if statements?
Below are the bind params:
$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
My personal preference is to put the default in the $where array. That way if you ever need to debug or track the values you get a complete look at what is being put into the array.
As far as where to bind the params, you will need to do it after you prepare the query so you will need a second set of if statements after your query is constructed.