0

I am creating a search engine for a book database.I have a radio button for exact search and similar search.My query is that how should i generate a SQL query of exact search.For eg I have ISBN and title as the field.Likewise I have many fields and they can be kept empty and populated too.How should i generate a SQL query for this query?

eg if the title is populated and isbn is populated then it should be

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

What if 10 fields are populated then how should i generate? Checking whether the filed is empty of not is a solution. But is there a better solution than this?

4

3 回答 3

4

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

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

然后,使用 for each 循环构造条件部分。

$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);
    }
}
于 2013-07-28T04:59:09.897 回答
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
}
于 2013-07-28T04:59:39.197 回答
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
}
于 2013-07-28T05:04:20.243 回答