对已过滤的查询进行php参数化查询

时间:2014-03-04 20:40:34

标签: php sql-injection parameterized-query

我正在根据用户正在应用的过滤器构建查询。一切都按照我想要的方式提取数据。我现在已经到了安全点。当我的“WHERE”可以添加多个过滤器时,如何使其安全。

$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()) {

}    

我按照你的意见制作了数组。我现在收到一个错误:mysqli_stmt :: bind_param()[mysqli-stmt.bind-param]:类型定义字符串中的元素数与绑定变量数不匹配。我的新代码是:

$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);

我可以将这样的数组用于bind_param吗?

1 个答案:

答案 0 :(得分:-2)

您需要清理输入!这是我通常使用的卫生功能:

function sanitize($string){
    $string = str_replace(array('"',"'"), array(""","'"),$string);
    $string = trim($string);
    $string = stripslashes($string);
    $string = mysql_real_escape_string($string);
    return $string;
}

像这样使用:

if ( !empty($sql_Year) ) $insertY .= " and Year='".sanitize($sql_Year)."'";
if ( !empty($sql_Model) ) $insertY .= " and Model='".sanitize($sql_Model)."'";
if ( !empty($sql_Style) ) $insertY .= " and Body='".sanitize($sql_Style)."'";
if ( !empty($sql_Color) ) $insertY .= " and Colour='".sanitize($sql_Color)."'";