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

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

抱歉,如果这令人困惑,请发表评论,如果您希望我重新解释这一点,我们将不胜感激!

最佳答案

与值绑定和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);
}
?>

关于php - PDO-按价格升序或降序排列,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12451519/

10-16 15:16