我正在尝试过滤数据库中的结果。我有一个类Filter,如下所示
<?php
class Filter{
protected $_dbHandle, $_dbInstance;
function search_car()
{
$this->_dbInstance = Database::getInstance();
$this->_dbHandle = $this->_dbInstance->getdbConnection();
$by_type = $_POST['by_type'];
$by_make = $_POST['by_make'];
$by_price = $_POST['by_price'];
$by_year_of_registration = $_POST['by_year_of_registration'];
$sql_query = "SELECT * FROM sta402_cars WHERE";
if ($by_type != "") {
$sql_query .= " type='$by_type'";
}
if ($by_make != "") {
$sql_query .= " make='$by_make'";
}
if ($by_price != "") {
$sql_query .= " price='$by_price'";
}
if ($by_year_of_registration != "") {
$sql_query .= " year_of_registration='$by_year_of_registration'";
}
$statement = $this->_dbHandle->prepare($sql_query); // prepare a PDO statement
$statement->execute(); // execute the PDO statement
return $statement;
}
}`
此课程的来电就在这里:
<?php if(isset($_POST['submit1'])) {
$filter = new Filter;
$retrieved_result = $filter->search_car($_POST);
$row = $retrieved_result->fetch();
$carData1 = new CarData($row);
foreach ($carData1 as $carData) {
echo '<tr> <td>' . $carData->getType() . '</td> <td>' . $carData->getMake() . '</td> <td>' . $carData->getModel() . '</td>
<td>' . $carData->getColour() . '</td> <td>' . $carData->getPrice() . '</td> <td>' . $carData->getYearOfRegistration() . '</td>
<td>' . $carData->getPicture() . '</td><td></tr>';
}
}
?>
我试图将echo放在过滤器类中,但没有任何改变。输出是..无。结果应该保持为空的位置,但所有其他内容都在页面上。我现在该怎么办?我该怎么办?
答案 0 :(得分:3)
这里有多个问题,第一个是您的查询可能是错误的。考虑这个$_POST
数据:
$_POST = [
'by_type' => 'minivan',
'by_year_of_registration' => '2011'
]
您生成的SQL将如下所示:
SELECT * FROM sta402_cars WHERE type='minivan' year_of_registration='2011'
您在这里缺少AND
条件。
您可以通过var_dump()
$sql_query
来解决这个问题,还需要检查$statement->execute()
上的返回值(它应该返回false
)。
您可以通过将WHERE
子句放在数组中来解决此问题,并implode(' AND ', $where)
另外这里有一个SQL注入漏洞,想象一下$_POST
就像这样:
$_POST = [
'by_type' => '\' OR is_hidden=1'
]
现在你的SQL是:
SELECT * FROM sta402_cars WHERE type='' OR is_hidden=1
显然这个例子可能是无害的,但也可能是破坏SQL。对此的解决方案是a)过滤输入,b)正确使用准备好的查询 ,这将逃避值:
$sql_query = "SELECT * FROM sta402_cars WHERE ";
$where = array();
$values = array();
if ($by_type != "") {
$where[] = "type = :type";
$values[':type'] = $by_type;
}
if ($by_make != "") {
$where[] = "make = :make";
$values[':make'] = $by_make;
}
if ($by_price != "") {
$where[] = "price = :price";
$values[':price'] = $by_price;
}
if ($by_year_of_registration != "") {
$where[] = "year_of_registration = :year";
$values[':year'] = $by_year_of_registration;
}
$sql_query .= implode(' AND ', $where);
$statement = $this->_dbHandle->prepare($sql_query); // prepare the query
$result = $statement->execute($values); // Pass in the values
if (!$result || $statement->rowCount() == 0) {
// query failed (invalid query, or no results)
} else {
// we have results
}
(您也可以将这些过滤器选项名称放在一个数组中,然后通过它们检查$ _POST,然后以这种方式构造$where
和$values
,而不是像这样线性化)