2012-10-16 121 views
0

我想$_GET一些变量,用户可以输入(正忙着做一个基本的Web服务器)的代码,这样的:无法弄清楚如何在PHP

$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(user和productID)将自动填充0或''(int/string)。

所以我想我可以用一个if声明:如果我有价格,或的productID和的productID作为用户变量的组合

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

但什么。

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

回答

2

您可以使用合并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 
} 
+0

因此。=向查询添加文本..不错,不知道,但isset()方法......这样做的工作,因为如果0已经在它或''其自动设置正确? – user1692174

+0

@ user1692174:据我所知,当没有设置变量(使用* GET *方法)时,它是* null *,而不是'0'。 – JCOC611

+0

它工作得很好! isset检查函数,如果它没有设置它不做任何事情..tnx!现在我需要搜索安全嘿嘿 – user1692174

0

您可以使用三元运算符来正确地作出查询字符串建立相应的查询,串联价格条款当它被设置。

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

你的英文不好,我们是巴西人O/

0
$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}'"; 

如果你想使用的变量别的东西。如果它们未在$_GET数据中设置,则将值设置为0""(空字符串)。

+0

如果你设置0或“”的查询结果将受到影响,所以我不能设置0或“” – user1692174