我有一个搜索表单,有3个文本框供用户输入。
Keyword text box
Name text box
Date text box
现在我必须设置6个"if"来满足用户的选择。
有没有办法让我不用写那么多"如果"?
如果用户选择填充所有3个文本框的示例代码:
SELECT * FROM <table> WHERE keyword=<keyword txbox> AND Name = <name txtbox> AND Date = <date txtbox>
这个结构将使您减少到3个if块。我写php不是为了让别人给你语法
select somefields
from sometables
where 1 = 3
and
(
if they filled out the keyword
or keyword = that variable
if they filled out the name
or name = that variable
if they filled out the date
or date = that variable
)
确保使用查询参数。还要确保你有一个没有完成文本框的计划。最后,如果日期字段包含时间组件,则在查询中处理它。
原始示例,未清理:
<?php
$op=array('keyword','name','date');
$_POST=array('keyword'=>'a','name'=>'b','date'=>'c');
$q="SELECT * FROM FOO WHERE ";
foreach ($op as $o){
if(!empty($_POST[$o])){
$q.= $o.' = "'.$_POST[$o].'" AND ';
}
}
$q=substr($q,0, -4);
echo $q; // SELECT * FROM FOO WHERE keyword = "a" AND name = "b" AND date = "c"
?>