目前我有一个简单的搜索查询,其工作原理如下:
$username = $_SESSION['username'];
$chosencategory = $_GET['category'];
$price = $_GET['price'];
$search = $_GET['search'];
$terms = explode(" ", $search);
if ($price && $chosencategory){
$sql = "SELECT * FROM people WHERE MATCH (lname,fname) AGAINST (:search IN BOOLEAN MODE) AND category='$chosencategory' ORDER BY price $price";
$q = $conn->prepare($sql) or die("failed!");
$q->bindValue(':search',"%".$search."%",PDO::PARAM_STR);
$q->execute();
}
当用户选择“显示价格从最低到最高”时,发送到$_GET['price']
= ASC的值,但我不确定这是否是一种安全的方式对结果进行排序,是否有人有更好的方法?
此方法也不是最好的,因为当用户选择排序选项,例如“显示价格从最低到最高”时,下拉框回显已发送到$ _GET ['price']的值,即“ASC” “所以在下拉框中,它会在表单发送后读取ASC!
很抱歉,如果这令人困惑请注释,如果您希望我重新解释一下,我们非常感谢任何帮助或建议!!
答案 0 :(得分:3)
与您的值绑定和SQL注入相关,您还应该在使用之前检查是否已设置值。如果您启用error_reporting(E_ALL)
,您会看到许多未定义的警告。以下是一些提示/更改:
<?php
// Check and set username
$username = (isset($_SESSION['username']) ? $_SESSION['username'] : 'guest');
// Check and set category
$category = (!empty($_GET['category']) ? $_GET['category'] : null);
// Check and set search
if(!empty($_GET['search'])){
$search = $_GET['search'];
$terms = explode(" ", $search);
}else{
$search = null;
$terms = null;
}
// Check that $_GET['price'] is ASC if not set to DESC
// as static values its ok to directly put in the query
if(isset($_GET['price']) && $_GET['price'] == 'ASC'){
$price = 'ASC';
}else{
$price = 'DESC';
}
if ($category !== null && $search !== null){
$sql = "SELECT *
FROM people
WHERE MATCH (lname,fname) AGAINST (:search IN BOOLEAN MODE)
AND category = :category
ORDER BY price ".$price;
$q = $conn->prepare($sql);
// Bind the params to the placeholders
$q->bindParam(':search', $search, PDO::PARAM_STR);
$q->bindParam(':category', $category, PDO::PARAM_STR);
$q->execute();
// Get result
$result = $q->fetchAll(PDO::FETCH_ASSOC);
}
?>