在php中搜索查询

时间:2013-10-28 14:15:35

标签: php mysql sql

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

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);

3 个答案:

答案 0 :(得分: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个新值,因此您可以看到此值不会出现在查询中。

答案 1 :(得分:0)

if(isset($_GET['your_variable'])){
  $whr = "column_name = $_GET['your_variable']";
}
else{
$whr = "1 = 1";
}

$qry ="SELECT * FROM table WHERE ".$whr;

答案 2 :(得分:0)

例如:

<?php
    $userSelectedValue = ...;

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

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

?>

然后考虑使用准备好的陈述更安全。