0

目前我有一个简单的搜索查询,其工作方式如下:

$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!

抱歉,如果这令人困惑,请发表评论,如果您希望我重新解释这一点,非常感谢任何帮助或建议!

4

1 回答 1

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);
}
?>
于 2012-09-18T14:30:14.853 回答