I have a database with student records, about 50 or so columns, all of which need to be searchable. I'm familiar with how to build a dynamic search query by appending fields. I can't seem to find any examples on searching a MySQL database using prepared statements that are dynamic in nature. For example, when searching you will only enter the fields you need to search by, so therefore, how do you build a dynamic prepared statement based on user input?
Here is an example of how to do it without prepared statements, however this is prone to SQL injection. I would need to "clean" each variable with a function. However, with a prepared statement this would be much more secure.
function clean($con,$var){
$var = trim($var);
$var = strtolower($var);
$var = mysqli_real_escape_string($con,$var);
return $var;
}
if(isset($_REQUEST['sub'])){
if(isset($_REQUEST['student_fname'])){
$student_fname = null;
if($_REQUEST['student_fname'] != ''){
$student_fname = '&& `student_fname` = \''.clean($con,$_REQUEST['student_fname']).'\' ';
}
}
if(isset($_REQUEST['student_lname'])){
$student_lname = null;
if($_REQUEST['student_lname'] != ''){
$student_lname = '&& `student_lname` = \''.clean($con,$_REQUEST['student_lname']).'\' ';
}
}
$sql = "SELECT * FROM `student_records`
WHERE 1=1
$student_fname
$student_lname
ORDER BY class ASC, student_lname ASC";
echo $sql;
}