2014-04-29 27 views
-1

我想創建一個表單,用戶可以在其中輸入信息然後搜索與此查詢匹配的表。我希望輸入的信息是可選的(不是所有的字段都需要完成)。我有第一個'如果'的工作只是地板和flatno,但不能得到第二個'如果添加'狀態'添加到查詢。帶有可選字段的PHP MySQL搜索

我知道我的代碼中的安全問題,但只想在內部服務器上使用它作爲自己的指導。

<?php 


// if there is a value in the floor and flatno field then do this: 
    if (!empty($_POST['Floor']) && (!empty($_POST['flatno']))) 
{ 
    require 'connectdb.php'; 
    $result = mysqli_query($con,"SELECT * FROM issuelog WHERE floor='$_POST[Floor]' AND flatnumber='$_POST[flatno]'"); 
} 

while($row = mysqli_fetch_array($result)) 
    { 

include("searchoutputform.php"); 
    } 

// second if - if there is something in the floor, flatno and status field then do this: 

elseif (!empty($_POST['Floor']) && (!empty($_POST['flatno'] && (!empty($_POST['status']))))) 
{ 
    require 'connectdb.php'; 
    $result = mysqli_query($con,"SELECT * FROM issuelog WHERE floor='$_POST[Floor]' AND flatnumber='$_POST[flatno]' AND status='$_POST[status]'"); 
} 

while($row = mysqli_fetch_array($result)) 
    { 

include("searchoutputform.php"); 
    } 
endif; 

// CLOSE CONNECTION TO DATABASE 
mysqli_close($con); 
?> 

更新:我已經刪除了所有的連接請求,所以現在只有1個!我收到以下錯誤:

Parse error: syntax error, unexpected T_BOOLEAN_AND, expecting ') (this is based on the second if)

+1

多少次你'需要「connectdb.php」;'整個???請基本的調試是_you_,而不是我們。 –

+0

方式(太多(很多(括號))) –

+0

如果您添加一個更新來說您修改了代碼,請修改我們可以看到的代碼,否則它會相當混亂! – halfer

回答

2

提示

你的第一個,如果總是執行如果這兩個值都在那裏,你ELSEIF不會再執行。只要將您的elseif更改爲另一個,如果

if (!empty($_POST['Floor']) && !empty($_POST['flatno'] && !empty($_POST['status'])) 
{ 
//... 
} 

爲什麼這麼說?這也是爲什麼

if(1==1 && 2==2) 
    { 
     echo "first if"; 
    } 
    elseif(1==1 && 2==2 && 3==3) 
    { 
    echo "this one will not execute even though the condition is true, due to elseif"; 
    } 
    if(1==1 && 2==2 && 3==3) 
    { 
    echo "Now this one will work"; 
    } 

這是一個基本的修復,但你應該簡化邏輯和構建那麼查詢追加值,如果他們是存在的。

而且你有一些額外的括號,和你有一些額外包括:)