【问题标题】:Cant figure out how to code this in php无法弄清楚如何在 php 中对此进行编码
【发布时间】:2012-10-16 22:14:29
【问题描述】:

我正在尝试$_GET 用户可能输入的一些变量(忙于制作基本的网络服务器):

$users= strval($_GET['user']);
$price= intval($_GET['price']);
$productID= intval($_GET['productid']);

这是我的查询:

$query = "SELECT * FROM `table` WHERE `user` = '" . $user . "' AND `price` <= " . $price . " AND `productID` = " . $productID; 

(类似这样的)

鉴于此理论链接:

www.example.com/api.php?price=300

并且不使用 GET 的其余部分(用户和产品 ID)将自动填充 0 或 ''(int/string)。

所以我想我可以使用if 声明:

if(price == 0){
   // change the query without the price as WHERE
}

但是,如果我将 price 和 productID 或 productID 和 user 组合为变量呢?

处理此问题的最佳方法是什么?也许这是一个愚蠢的问题,但我无法弄清楚。

【问题讨论】:

    标签: php


    【解决方案1】:

    如果提供了变量,您可以使用组合的 IF 语句来构建适当的查询(如果没有提供则忽略它们)

    $query = "SELECT * FROM `table` WHERE 1"; // WHERE 1 means "return all rows from table"
    
    if ( isset( $_GET['price'] ) ){ // Only if price variable is set
        $query .= " AND price <= '{$_GET['price']}'"; // Restrict results by price
    }
    
    if ( isset( $_GET['user'] ) ){ // Only if user variable is set
        $query .= " AND user LIKE '{$_GET['user']}'"; // Restrict results by user
    }
    
    if ( isset( $_GET['productID'] ) ){ // Only if user variable is set
        $query .= " AND productID = '{$_GET['productID']}'"; // Restrict results by productID
    }
    

    【讨论】:

    • so .= 将文本添加到查询中.. nice 不知道,但是 isset() 方法...会起作用吗,因为如果 0 已经在其中或 '' 它会自动设置正确?
    • @user1692174:据我所知,当未设置变量时(使用 GET 方法)它是 null,而不是 @ 987654322@.
    • 效果很好! isset 检查该功能,如果它没有设置它不做任何事情..tnx!现在我需要搜索安全性呵呵
    【解决方案2】:

    您可以使用三元运算符正确制作查询字符串,在设置价格子句时连接它。

    $query = "select * from table where user = $user" . ($price ? " AND price <= $price" : "") . " AND productID = $productID";
    

    你的英语很差,我们是巴西人 o/

    【讨论】:

      【解决方案3】:
      $users = $_GET['user'] || "";
      $price = $_GET['price'] || 0;
      $productID = $_GET['productid'] || 0;
      $query = "SELECT * FROM table WHERE 1";
      
      $query .= (isset($_GET['user'))?"AND user = '{$users}'";
      $query .= (isset($_GET['price'))?"AND price <= '{$price}'";
      $query .= (isset($_GET['productid'))?"AND productID = '{$productID}'";
      

      如果您想将变量用于其他用途。这会将值设置为 0""(空字符串),如果它们未在 $_GET 数据中设置。

      【讨论】:

      • 如果设置0或""会影响查询结果,所以不能设置0或""
      猜你喜欢
      • 2013-04-10
      • 2015-07-04
      • 2013-03-05
      • 1970-01-01
      • 2013-04-03
      • 1970-01-01
      • 1970-01-01
      • 2015-11-13
      • 1970-01-01
      相关资源
      最近更新 更多