I am building a query based on filters that are being applied by the user. Everything works the way I want to with pulling the data. I have come now to the point of security. How can I make this secure when my "WHERE" could have multiple filters added in.
$sql_Year = $_GET['year'];
$sql_Model = $_GET['model'];
$sql_Style = $_GET['style'];
$sql_Color = $_GET['color'];
if ( !empty($sql_Year) ) $insertY .= " and Year='$sql_Year'";
if ( !empty($sql_Model) ) $insertY .= " and Model='$sql_Model'";
if ( !empty($sql_Style) ) $insertY .= " and Body='$sql_Style'";
if ( !empty($sql_Color) ) $insertY .= " and Colour='$sql_Color'";
$stmt = $con->prepare("SELECT DISTINCT(`Year`) FROM `cars` WHERE `New/Used` = 'N' ".$insertY." ORDER BY `Year` ASC ");
$stmt->execute();
$stmt->bind_result($Year);
while ($row = $stmt->fetch()) {
}
I followed your advice and made arrays. I am now getting a error: mysqli_stmt::bind_param() [mysqli-stmt.bind-param]: Number of elements in type definition string doesn't match number of bind variables. My new code is:
$get_Year = $_GET['year'];
$get_Model = $_GET['model'];
$get_Style = $_GET['style'];
$get_Color = $_GET['color'];
$YearArray = array();
$YearValues .= "WHERE `New/Used`=?";
$YearTypes .= "s";
array_push($YearArray, "U");
if ($get_Year != "") {
$YearValues .= " and `Year`=?";
$YearTypes .= "s";
array_push($YearArray, "2004");
}
if ($get_Model != "") {
$YearValues .= " and Model=?";
$YearTypes .= "s";
array_push($YearArray, $get_Model);
}
if ($get_Style != "") {
$YearValues .= " and Body=?";
$YearTypes .= "s";
array_push($YearArray, $get_Style);
}
if ($get_Color != "") {
$YearValues .= " and Colour=?";
$YearTypes .= "s";
array_push($YearArray, $get_Color);
}
$YearVariables = implode(',', $YearArray);
$stmt = $con->prepare("SELECT DISTINCT(`Year`) FROM `cars` ".$YearValues." ORDER BY `Year` ASC ");
$stmt->bind_param($YearTypes, $YearVariables);
$stmt->execute();
$stmt->bind_result($Year);
Can I use the arrays like this for bind_param?