我必须建立一个汽车网站,根据预设的mysql数据库过滤汽车。 我已经让它过滤如果所有都被选中(例如:本田,白色,汽油而不是特殊 - 它会显示那辆车)但是如果我只是想看到所有的本田(例如)没有任何显示。
这是我的代码:
if(isset($_GET['make']) || isset($_GET['colour']) || isset($_GET['fueltype']) || isset($_GET['special'])){
if(isset($_GET['make'])){
$make = $_GET['make'];
}
if(isset($_GET['colour'])){
$colour = $_GET['colour'];
}
if(isset($_GET['fueltype'])){
$fueltype = $_GET['fueltype'];
}
if(isset($_GET['special'])){
$special = $_GET['special'];
}
$result = mysqli_query($con,"SELECT * FROM Cars WHERE MAKE ='$make' AND COLOUR = '$colour' AND FUELTYPE = '$fueltype' AND SPECIAL = '$special'");
}
else{
$result = mysqli_query($con,"SELECT * FROM Cars");
}
else语句会在您过滤之前打开页面时显示所有车辆。
答案 0 :(得分:0)
escape可以表示:mysql_escape_string,检查有效/允许值的列表,或者在思考后想要的任何内容。
$where = "";
$separator = " WHERE ";
if(isset($_GET['make'])){
$make = $_GET['make'];
!! escape here
$where .= $separator . " MAKE = '$make' ";
$separator = " AND ";
}
if(isset($_GET['colour'])){
$colour = $_GET['colour'];
!! escape here
$where .= $separator . " COLOUR = '$colour' ";
$separator = " AND ";
}
...
$result = mysqli_query($con,"SELECT * FROM Cars " . $where);
答案 1 :(得分:0)
以下是如何做到这一点。请为sql注入攻击做些什么。这只是一个例子。
$query = "SELECT * FROM Cars ";
$where = array();
if(isset($_GET['make'])){
$where['make'] = $_GET['make'];
}
if(isset($_GET['colour'])){
$where['colour'] = $_GET['colour'];
}
if(isset($_GET['fueltype'])){
$where['fueltype'] = $_GET['fueltype'];
}
if(isset($_GET['special'])){
$where['special'] = $_GET['special'];
}
$string = '';
if(count($where)>0){
$i=0;
foreach($where as $key => $value)
{
if($i==0){
$string .= " WHERE $key = $value ";
}else{
$string .= " AND $key = $value ";
}
$i++;
}
}
$query .= $string;
mysqli_query($query);
答案 2 :(得分:0)
if(isset($_GET['make']) || isset($_GET['colour']) || isset($_GET['fueltype']) || isset($_GET['special'])){
$where="WHERE ";
if(isset($_GET['make'])){
$make = $_GET['make'];
$where .="MAKE ='$make' AND";
}
if(isset($_GET['colour'])){
$colour = $_GET['colour'];
$where .="COLOUR = '$colour' AND";
}
if(isset($_GET['fueltype'])){
$fueltype = $_GET['fueltype'];
$where .="FUELTYPE = '$fueltype' AND";
}
if(isset($_GET['special'])){
$special = $_GET['special'];
$where .="SPECIAL = '$special";
}
$where=rtrim($where,'AND');
$result = mysqli_query($con,"SELECT * FROM Cars".$where);
}
else{
$result = mysqli_query($con,"SELECT * FROM Cars");
}
答案 3 :(得分:0)
忽略安全问题,您可以使用以下内容替换整个代码:
$query = "SELECT * FROM Cars WHERE 1 = 1";
if (isset($_GET['make']))
$query .= ' AND MAKE = ' . (int) $_GET['make'];
if (isset($_GET['colour']))
$query .= ' AND COLOUR = ' . (int) $_GET['colour'];
if (isset($_GET['fueltype']))
$query .= ' AND FUELTYPE = ' . (int) $_GET['fueltype'];
if (isset($_GET['special']))
$query .= ' AND SPECIAL = ' . (int) $_GET['special'];
$result = mysqli_query($con, $query);