[英]PHP MySQL search with optional fields
我正在嘗試創建一個表單,用戶可以在其中輸入信息,然后搜索與該查詢匹配的表。 我希望輸入的信息是可選的(並非所有字段都需要填寫)。 我有第一個'if'僅適用於樓板和Flatno,但無法獲得第二個'if',並且在查詢中添加了'status'。
我知道代碼中的安全性問題,但是只想在內部服務器上使用它作為自己的指南。
<?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個! 我收到以下錯誤:
解析錯誤:語法錯誤,意外的T_BOOLEAN_AND,期望為')(這基於第二個if)
暗示
如果這兩個值都存在,則第一個if始終執行,否則elseif則不執行。 只需將elseif更改為另一個if
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";
}
這是一個基本解決方案 ,但是您應該簡化邏輯並構建查詢,然后將值附加到查詢中(如果存在)。
而且您還有一些額外的括號,並且還有一些額外的內容:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.