2012-12-03 76 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 
    ); 

这接缝工作得很好,但我很确定它应该是一个更优雅的解决方案。