2013-07-28 19 views
0

我正在为图书数据库创建一个搜索引擎。我有一个单选按钮,用于精确搜索和类似的搜索。我的查询是,我应该如何生成一个精确搜索的SQL查询。例如,我有ISBN和标题作为字段。同样,我有很多领域,他们可以保持空白,也填充太多。我应该如何生成此查询的SQL查询?我应该如何在PHP中生成动态查询字符串?

例如,如果标题填充,ISBN填充,那么它应该是

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

如果10个字段填充那怎么产生?检查该字段是否为空是解决方案。但是有没有比这更好的解决方案?

回答

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}"; 
    } 
} 

使用准备语句来防止SQL注入。

$sh = $db->prepare($sql . " WHERE " . $condition); 
foreach($search as $key => $value) { 
    if (isset($value) && ($value != "")) { 
     if ($condition != "") { 
      $condition .= " AND "; 
     } 
     $sh->bindValue(":{$key}", $value); 
    } 
} 
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 
} 
+0

没有归属于Munroe先生? :) –

+0

它在替代文本中,我认为StackOverflow也使它成为标题文本。呵呵... –

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 
}