变量sql查询取决于搜索参数的数量

时间:2014-09-29 11:44:23

标签: php sql

我需要在php中进行sql查询以搜索一些条目(所以使用WHERE)。但是用于搜索的字段可能是可变数字。

我有一个带有搜索表单的页面,有4个字段。它通过POST字段发送到search.php进行查询:

$gomme_sql = $data->query("SELECT * FROM table WHERE parameter1 = '$_POST['name1']' AND parameter2 = '$_POST['name2']' ORDER BY id ASC");

但我不知道填写了哪个字段。因此,如果我没有在搜索表单的field1中输入任何内容,我在WHERE查询中不应该有parameter1 = '$_POST['name1']'

你知道如何获得这个吗?

谢谢

2 个答案:

答案 0 :(得分:0)

您可以在以下列方式将该子句附加到查询之前检查帖子数据:

编辑:添加额外的支票:

$sql="select something from someTable ";
if(!empty($_POST['name1']) || !empty($_POST['name2'])) // add as many as you like
{
$sql.=" where ";
    if(!empty($_POST['name1']))
    {
        $sql.="parameter1= $_POST['name1']";
    }
// etc etc...
}
$sql.=" ORDER BY id ASC";

等等。

话虽如此,请使用来自用户的这种输入的准备好的陈述。这是对SQL注入的超级开放。请阅读:How can I prevent SQL injection in PHP?

答案 1 :(得分:0)

您可以像这样编写通用的sql select函数,如果需要更复杂的SQL,只需修改它。

    <?php


     function sqlSelect($table, $sel, $wh = '', $groupby = '', $order = '', $add = '') {

            $tb = $table;
            if (is_array($table)) {
                $tb = implode(',', $table);
            }
            if ($wh) {
                if (is_array($wh)) {
                    $w = array();
                    foreach ($wh as $k => $v) {
                        $v = mysqli_real_escape_string($v);
                        if (is_null($v))
                            $w [] = "$k=null ";
                        else
                            $w [] = "$k ='$v'";
                    }
                    $wh = 'where ' . implode(' and ', $w);
                }else {
                    $wh = "where $wh";
                }
            }
            if ($groupby)
                $groupby = "group by $groupby";
            if ($order)
                $order = "order by $order";
            $sql = "select $sel from $tb $wh $groupby $order $add ";
            return $sql;
        }
    //set _GET as this is console test    
    $_GET['name1']='Bob';
    $where = array(
        'name1'=>$_GET['name1']
    );
        echo sqlSelect('sometable' , '*' , $where) ."\n";
        // select * from sometable where name1 ='Bob'    

//or some complex stuff
        echo sqlSelect('persons', "age,status" , array('name'=>'Maria' , 'likes'=>'PHP') , null,  'age' , 'limit 20');
       //select age,status from persons where name ='Maria' and likes ='PHP'  order by age limit 20