我应该如何在php中生成动态查询字符串?

时间:2013-07-28 04:47:40

标签: php mysql

我正在为图书数据库创建一个搜索引擎。我有一个用于精确搜索和类似搜索的单选按钮。我的查询是如何生成精确搜索的SQL查询。例如我有ISBN和标题作为field.Likewise我有很多字段,它们可以保持为空并填充。如何为此查询生成SQL查询?

例如,如果填充了标题并且填充了isbn,那么它应该是

select * from book_info where isbn="$_POST['isbn']" and title="$_POST['title']"

如果填充了10个字段,那么我应该如何生成呢?检查存档是否为空是一种解决方案。但是有比这更好的解决方案吗?

3 个答案:

答案 0 :(得分:4)

您可以将所有选项放在列表中,如下面的代码。

$search = array("isbn" => $_POST['isbn'],
                "title" => $_POST['title'],
                "table_field" => $input_value);

然后,使用每个循环来构造条件部分。

$sql = "SELECT * FROM book_info";
$condition = "";
foreach($search as $key => $value) {
    if (isset($value) && ($value != "")) {
        if ($condition != "") {
            $condition .= " AND ";
        }
        $condition .= "{$key}=:{$key}";
    }
}

使用prepare语句来阻止SQL注入。

$sh = $db->prepare($sql . " WHERE " . $condition);
foreach($search as $key => $value) {
    if (isset($value) && ($value != "")) {
        if ($condition != "") {
            $condition .= " AND ";
        }
        $sh->bindValue(":{$key}", $value);
    }
}

答案 1 :(得分:2)

xkcd

除此之外,要点......

尝试这样的事情:

$allowed_keys = ["isbn","title",...]; // or array("isbn"...) if you're not up-to-date
$postvars = array_intersect_key($_POST,array_flip($allowed_keys));
$conditions = []; // or array(); for old PHP
foreach($postvars as $k=>$v) {
    $conditions[] = "`".$k."`='".mysql_real_escape_string($v)."'";
    // use whatever function is suitable for the library you're using
    // I'm assuming the basic mysql library, based on your injection vulnerability
}
if( $conditions) {
    $query = "select * from `book_info` where ".implode(" and ",$conditions);
    // run query
}

答案 2 :(得分:1)

不要那样做。你正在做的是邀请SQL注入攻击,这使你的网站容易受到攻击。

在PHP中,使用PDO和参数化查询。

$isbn = $_POST['isbn'] . '';
$title = $_POST['title'] . '';


$db = new PDO( "host", "user", "pass");
$stm = $db->prepare( "select id, name, title, whatever from book_info where isbn= ? and and title= ?");
$stm->bindParam( 1, $isbn);
$stm->bindParam( 2, $title);
$stm->execute();
while ($row = $stm->fetchObject())   //or just fetch()
{
   $othervar = $row->name;
   //etc
}