2012-12-03 107 views
1

我想我在這裏閱讀所有的文章,但仍然無法讓我的代碼工作100%。我是一個PHP表單,用戶可以根據4個位置中的任意一個進行搜索,或者可以完全跳過搜索,在這種情況下,應跳過'where location'子句並移至下一個參數組。我的MySQL存儲過程是這樣的:mysql存儲過程skip null參數

CREATE PROCEDURE search( 
    IN inRoomsPerPage INT, 
    IN inStartItem INT, 
    IN inAddDate INT, 
    IN inLocation1 ENUM('T','F'), 
    IN inLocation2 ENUM('T','F'), 
    IN inLocation3 ENUM('T','F'), 
    IN inLocation4 ENUM('T','F') 
) 
BEGIN 
SELECT * 
FROM useradds as ua 
INNER JOIN household as hh on hh.idx_user_id = ua.idx_user_id 
INNER JOIN house as h on h.idx_user_id = ua.idx_user_id 
WHERE adddate >= (CURDATE() - INTERVAL inAddDate DAY) AND 
((inLocation1 IS NULL OR downtown = inLocation1) OR 
(inLocation2 IS NULL OR hwy = inLocation2) OR 
(inLocation3 IS NULL OR dewey = inLocation3) OR 
(inLocation4 IS NULL OR lewes = inLocation4)) 
ORDER BY ua.adddate DESC 
LIMIT inStartItem, inRoomsPerPage; 
END$$ 

每當我選擇任意一個或多個位置,但如果我嘗試跳過它不工作,這工作正常(它應該只是選擇在最後inAddDate一切) 。 如果我更換

(inLocation1 IS NULL OR downtown = inLocation1) 

downtown = COALESCE(NULLIF(inLocation1, ''), downtown)) 

然後選擇一切,如果我繞過的位置,但如果我想任何2個或多個位置做搜索不返回任何東西。我確信有一個很好的方法來解決這個問題,因爲我有更多的參數組添加。

+0

你是什麼意思的「跳過」?能否請您澄清一下,理想情況是輸入實例和預期結果,您希望發生什麼以及何時發生。 – Bohemian

+0

當然。所以PHP/HTML部分搜索在四個主要地點的房屋出租增加郵件。然而,搜索提供了多種選擇:租金,吸菸習慣等等,全部採用相同的形式。在大多數用戶輸入的形式是複選框: –

+0

價值來自哪裏是無關緊要的。我在談論參數值和預期行爲。儘可能清晰和精確。就目前而言,你的問題含糊不清。 – Bohemian

回答

0

我的PHP/HTML部分看起來是這樣的:

<form action='' method='post' > 
    <select name='ckadddate'> 
     <option value='1'>last 24 hours</option> 
     <option value='3' selected>last 3 days</option> 
     <option value='7'>last week</option></select> 
in:<input type='checkbox' name='Downtown' >Downtown 
    <input type='checkbox' name='Hwy' >HWY 1 
     <input type='checkbox' name='Dewey'>Dewey 
     <input type='checkbox' name='Lewes'>Lewes 
<input name='SubmitSearch' type='submit' value='Search'> 

正在調用存儲過程的PHP函數的部分是:

if(isset($_POST['SubmitSearch'])){ 
    $cklocation1 = $cklocation2= $cklocation3= $cklocation4= ''; 
    if(isset($_POST['Downtown']))$cklocation1 = 'T'; 
     if(isset($_POST['Hwy']))$cklocation2 = 'T'; 
     if(isset($_POST['Dewey']))$cklocation3 = 'T'; 
     if(isset($_POST['Lewes']))$cklocation4 = 'T'; 
    **if(!isset($_POST['Downtown']) && !isset($_POST['Hwy']) && !isset($_POST['Dewey']) && !isset($_POST['Lewes'])){ 
     $cklocation1 = $cklocation2= $cklocation3= $cklocation4= 'T'; 
    }** 
$sql = 'CALL search_room(:RoomsPerPage, :StartItem,:Adddate, 
:Location1,:Location2,:Location3,:Location4)'; 
$params = array (':RoomsPerPage' => ADDS_PER_PAGE, ':StartItem' => $start_item, 
':Adddate' => $_POST['ckadddate'],':Location1' => $cklocation1, 
':Location2' => $cklocation2, ':Location3' => $cklocation3, ':Location4' => $cklocation4 
    ); 

這接縫工作得很好,但我很確定它應該是一個更優雅的解決方案。