我是PHP的新手,所以对以下任何帮助都会非常感激:
我正在尝试使用WHERE条件运行查询,但我只想在已设置变量的情况下应用where条件(通过单选按钮)。
我基本上希望能够说 - 如果未设置变量,请不要将其包含在where条件中。复杂的是,我将使用3个以上的变量进行此操作......
最基本的 - 这是我到目前为止的代码:
if(isset($_POST['category'])){
$category = $_POST['category'];}
if(isset($_POST['brand'])) {
$brand = $_POST['brand'];
}
{
$q = 'SELECT name, category, brand, price, imageurl, purchaselink FROM clothes WHERE category = "'.$_POST['category'].'" AND brand = "'.$_POST['brand'].'"';
[截短]
非常感谢!
答案 0 :(得分:1)
您可以使用数组执行此操作,但首先不要以这种方式构建查询,因为您将容易受到SQL注入攻击。请改用PDO。
我们的想法是列出合适的条件:
$conds = [ 'brand', 'category', 'name' ];
$where = [ ]; // Empty array
foreach ($conds as $cond) {
if (!empty($_POST[$cond])) {
$sql = "({$cond} = ?)"; // We use PDO and bound values.
$where[$sql] = $_POST[$cond];
// In *deprecated* MySQL we would use at least
// $sql = "({$cond} = '" . mysql_real_escape_string($_POST[$cond]) . "')";
// $where[$sql] = true;
}
}
// Now we have a list of pairs:
// brand = ? => 'MyBrand',
// name = ? => 'MyName',
if (!empty($where)) {
$sql_string .= ' WHERE (';
$sql_string .= implode( ' AND ', array_keys($where) );
$sql_string .= ')';
}
// $sql_string is now SELECT ... WHERE ( (brand=?) AND (name=?) ... )
// Using the MySQL version, we would have ... WHERE ( (brand='MyBrand') AND ... ) )
// With PDO we PREPARE the query using sql_string
// http://dev.mysql.com/doc/apis-php/en/apis-php-pdo-mysql.html
// http://www.php.net/manual/en/intro.pdo.php
// We need an open PDO connection saved into $pdo
$stmt = $pdo->prepare ($sql_string);
// Then we execute the query.
// Bind the values to array_values($where).
$stmt->execute( array_values($where) );
while ($tuple = $stmt->fetch(PDO::FETCH_ASSOC)) {
...
}
更短的方式,只有MySQL(因为它不区分键和值)将是
$where = [ ]; // empty array()
foreach ($conds as $cond) {
if (empty($_POST[$cond])) {
continue;
}
// THIS IS NOT SECURE. See e.g. http://johnroach.info/2011/02/17/why-mysql_real_escape_string-isnt-enough-to-stop-sql-injection-attacks/
$escaped = mysql_real_escape_string($_POST[$cond]);
$where[] = "({$cond} = '{$escaped}')";
}
$query = "SELECT ...";
if (!empty($where)) {
$query .= " WHERE (" . implode(' AND ', $where) . ")";
}
这种方法还有一个额外的好处,就是你可以对'AND'进行参数化 - 用户可以通过无线电按钮选择是否具有ANDed或ORed条件:
$and_or = ('OR' == $_POST['andor']) ? ' OR ' : ' AND ';
$query .= " WHERE (" . implode($and_or, $where) . ")";
请注意,不使用'andor'的实际值 - 如果是OR,则使用“OR”。客户在POST中意外发送的任何其他信息(例如“--; DROP TABLE Students;”)均被视为“AND”。
答案 1 :(得分:0)
你必须在if(){}
中包含所有内容 if(isset($_POST['category']) && isset($_POST['brand'])){
$q = 'SELECT name, category, brand, price, imageurl, purchaselink FROM clothes WHERE category = "'.$_POST['category'].'" AND brand = "'.$_POST['brand'].'"';
}
答案 2 :(得分:0)
我使用这种技术来制作我的过滤器:
$q = 'SELECT name, category, brand, price, imageurl, purchaselink FROM clothes WHERE 1=1 ';
if(isset($_POST['category'])) $q .= ' AND category ="'.$_POST['category'].'"';
if(isset($_POST['brand'])) $q .= ' AND brand = "'.$_POST['brand'].'"';
// here you can add other filters. :) be happy