2017-10-10 64 views
2

我有這個音樂網站,我有一個搜索側欄,我希望人們能夠從我的表中找到正確的音樂家個人資料。搜索表單使用複選框構建,並使用PHP和MySQL連接到我的表格。我希望人們能夠從類別中找到配置文件,例如位置,用戶類型,他們播放的音樂流派以及是否有專輯發佈。查詢搜索與多個複選框名稱

<form action="udforsk.php" method="post" enctype="multipart/form-data"> 
    <h2>User type</h2> 
    <input type="checkbox" name="type[]" value="Solo"> 
    <input type="checkbox" name="type[]" value="Duo"> 
    <input type="checkbox" name="type[]" value="Band"> 

    <h2>Location</h2> 
    <input type="checkbox" name="location[]" value="area_1"> 
    <input type="checkbox" name="location[]" value="area_2"> 
    <input type="checkbox" name="location[]" value="area_3"> 
    <input type="checkbox" name="location[]" value="area_4"> 
    <input type="checkbox" name="location[]" value="area_5"> 

    <h2>Genre</h2> 
    <input type="checkbox" name="genre[]" value="genre_1"> 
    <input type="checkbox" name="genre[]" value="genre_2"> 
    <input type="checkbox" name="genre[]" value="genre_3"> 
    <input type="checkbox" name="genre[]" value="genre_4"> 
    <input type="checkbox" name="genre[]" value="genre_5"> 

    <h2>Album or demo</h2> 
    <input type="checkbox" name="release[]" value="album"> 
    <input type="checkbox" name="release[]" value="demo"> 
</form> 

我希望這被連接到一個查詢寬度,但我有問題如何處理一些類別沒有被填寫的搜索。如果沒有選中地點複選框,則查詢搜索中所有地點都是公平的遊戲。

現在我試圖用IN來搜索用戶,我的查詢看起來像這樣,但當$ _POST輸入爲空時,它給我帶來麻煩。現在我只是試圖使它與地點和流派合作。

$sql = "SELECT artist.ArtistID, artist.ArtistName, artist.RegionID, 
artist_genre.ArtistID, artist_genre.GenreID 
FROM artist, artist_genre 
WHERE artist.RegionID IN ($areaer) AND artist_genre.GenreID IN ($genrer)"; 

所有幫助如何使用多個搜索變量與多個搜索變量一般複選框將是很多的幫助。

+0

[PHP:檢查是否有任何張貼的變量是空的](https://stackoverflow.com/questions/3190464/php-check-if-any-posted-vars-are-empty-form-all-fields-required ) –

+0

[檢查$ _POST-value是否爲空](https://stackoverflow.com/questions/9154719/check-whether-post-value-is-empty) –

+0

如果你想有一個默認值,你可以使用輸入類型=「隱藏」,所以如果沒有勾選它會發布默認值 –

回答

0

你可以試試這個代碼:

$conditions = []; 
$query = 'your query '; 
$conditions[] = isset($_POST['location']) ? 'artist.RegionID in ('.implode(',',$_POST['location']).')'; 
$conditions[] = isset($_POST['genre']) ? 'artist.GenreID in ('.implode(',',$_POST['genre']).')'; 
if(sizeof($conditions) > 0) query.='where '.implode(' and ',conditions); 

但它是更好,如果你有準備好的聲明中工作。