我有四個搜索字段用於搜索數據庫中的書籍ID:s,然後回顯結果。根據您選擇從sql查詢中搜索的所選字段,您可以在下面的代碼中看到。標題和isbn字段工作正常,但當我嘗試使用作者或類別字段沒有得到返回。相關數據庫表格也可以在下面看到。也許有什麼問題,我使用SQL函數LIKE?使用LIKE和通配符搜索數據庫
數據庫:
CREATE TABLE IF NOT EXISTS `bok` (
`bokId` int(11) NOT NULL AUTO_INCREMENT,
`bokTitel` varchar(100) DEFAULT NULL,
`upplaga` varchar(100) DEFAULT NULL,
`ISBN` varchar(30) DEFAULT NULL,
PRIMARY KEY (`bokId`)
)
CREATE TABLE IF NOT EXISTS `skrivenav` (
`bokId` int(11) DEFAULT NULL,
`fId` smallint(6) DEFAULT NULL
)
CREATE TABLE IF NOT EXISTS `forfattare` (
`fId` smallint(6) NOT NULL,
`fNamn` varchar(80) DEFAULT NULL,
PRIMARY KEY (`fId`)
)
CREATE TABLE IF NOT EXISTS `bokkat` (
`bokId` int(11) DEFAULT NULL,
`katId` smallint(6) DEFAULT NULL
)
CREATE TABLE IF NOT EXISTS `kategori` (
`katId` smallint(6) NOT NULL,
`katNamn` varchar(80) DEFAULT NULL,
PRIMARY KEY (`katId`)
)
PHP代碼:
<?php
$q = "SELECT DISTINCT bokId FROM ";
if($_GET['search_title']!=""||$_GET['search_ISBN']!=""){
$q = $q."(SELECT * FROM bok WHERE ";
if($_GET['search_title']!="")
$q = $q."bokTitel LIKE '%$_GET[search_title]%' ";
if($_GET['search_title']!="" && $_GET['search_ISBN']!="")
$q = $q."AND ";
if($_GET['search_ISBN']!="")
$q = $q."ISBN LIKE '%$_GET[search_ISBN]%' ";
$q = $q.") AS F";
}
else $q = $q."bok";
if($_GET['search_author']!=""){
$author = explode(",", $_GET['search_author']);
$auth = "";
foreach ($author as $value){
$auth = $auth . "%" . $value . "%', '";
}
$auth = trim($auth, ", '");
$q = $q." NATURAL JOIN (SELECT * FROM skrivenav NATURAL JOIN forfattare WHERE fNamn LIKE ('$auth')) AS S ";
}
if($_GET['search_category']!="") {
$category = explode(",", $_GET['search_category']);
$cat = "'";
foreach ($category as $value){
$cat = $cat . "%" . $value . "%', '";
}
$cat = trim($cat, ", '");
$q = $q." NATURAL JOIN (SELECT * FROM bokkat NATURAL JOIN kategori WHERE katNamn LIKE ('$cat')) AS K ";
}
$rs = mysql_query($q);
confirm_query($rs);
while($row = mysql_fetch_row($rs)){
echo $row[0]."<br />";
}
?>
與作者字段進行搜索時生成的查詢: SELECT DISTINCT bokId FROM書 自然連接(SELECT * FROM skrivenav NATURAL JOIN for fattare 其中fNamn LIKE('%Jonas%','%Alex%'))作爲S
從anthares答案快速解決方案,它的工作,所以謝謝你!
如果($ _ GET [ 'search_author'] = 「」!){
$author = explode(",", $_GET['search_author']);
$auth = "";
$q = $q. " NATURAL JOIN (SELECT * FROM skrivenav NATURAL JOIN forfattare WHERE fNamn LIKE ";
foreach ($author as $value){
$auth = $auth . "%" . $value . "%'";
$q = $q. "'$auth OR ";
$auth = "";
}
$q = trim($q, " OR");
$q = $q. ") AS A";
}
請發佈導致錯誤結果的生成查詢。這將使它更容易幫助。 – 2010-02-18 10:50:33