0

我通过 GET 方法传递变量在 php 中创建搜索查询。当变量为空时,它会传递查询,例如,

SELECT * FROM table WHERE column_name = null.

它显示错误(很明显)。我想创建类似的查询。如果用户没有从搜索选项中选择任何内容,那么它应该从该列中获取所有数据。

正确的逻辑是什么?谢谢。

代码:

if(isset($_GET['selPetType']) && $_GET['selPetType'] != '')
{
     $searchParams['petType'] = $_GET['selPetType'];
     $queryStr .= " PetType='" .$_GET['selPetType']. "'";
}

if(isset($_GET['txtPetBreed1']) && !empty($_GET['txtPetBreed1']))
{
    $searchParams['breed'] = $_GET['txtPetBreed1'];
    $queryStr .= " AND PetBreed1 ='". $_GET['txtPetBreed1'] . "'";
}


$clause1 = "SELECT * FROM pet WHERE $queryStr ORDER BY `Avatar` ASC LIMIT $startLimit, $pageLimit";
$totalRun1 = $allQuery->run($clause1);
4

3 回答 3

1

也许是这样的:

    $get['param1'] = 'foo';
    $get['param3'] = null;
    $get['param2'] = '';
    $get['param4'] = 'bar';

    $where = null;

    foreach ($get as $col => $val) {
        if (!empty($val)) {
            $where[] = $col . ' = "' . $val . '"';
        }
    }

    $select = 'SELECT * FROM pet ';
    if ($where) {
        $select .= 'WHERE ' . implode(' AND ', $where);
    }
    $select .= ' ORDER BY `Avatar` ASC LIMIT $startLimit, $pageLimit';

编辑:我添加if以删除空值并向示例添加 2 个新值,因此您可以看到这些值不会在查询中。

于 2013-10-28T14:29:14.010 回答
0

例如 :

<?php
    $userSelectedValue = ...;

    $whereCondition = $userSelectedValue ? " AND column_name = " . $userSelectedValue : "" ; 

    $query = "SELECT * FROM table WHERE 1" . $whereCondition; 

?>

然后考虑使用准备好的语句更安全。

于 2013-10-28T14:19:39.973 回答
0
if(isset($_GET['your_variable'])){
  $whr = "column_name = $_GET['your_variable']";
}
else{
$whr = "1 = 1";
}

$qry ="SELECT * FROM table WHERE ".$whr;
于 2013-10-28T14:19:14.620 回答