我有一个搜索表单,其中包含四个过滤器文本框。我想要做的是每当用户提交表单时,只会提交和搜索具有值的文本框。我知道如何在if语句中执行它,但是在代码中编写它太长了。还有其他更短的方法吗?
答案 0 :(得分:1)
Process.php
<?php
if (($_POST['First'])== TRUE);
$Fv = $_POST['First'];
if(($_POST['Second'])== TRUE);
$Sv = $_POST['Second'];
if(($_POST['Third'])!= TRUE);
$Tv = $_POST['Third'];
if(($_POST['Fourth'])!= TRUE);
$Fov = $_POST['Fourth'];
echo $Fv;
echo"</br>";
echo $Sv;
echo"</br>";
echo $Tv;
echo"</br>";
echo $Fov;
?>
的search.php
<?php
echo '<html>
<body>
<form action="process.php" method="post">
First: <input type="text" name="First"><br>
Second: <input type="text" name="Second"><br>
Third: <input type="text" name="Third"><br>
Fourth: <input type="text" name="Fourth"><br>
<input type="submit">
</form>
</body>
</html> ';
?>
仅回输输入的值。
答案 1 :(得分:1)
试试这个 的search.php
$sql = " select * from table name where 1=1 "
if (($_POST['First'])!='');
$sql .= ' AND first = "'.$_POST['First'].'"';
if(($_POST['Second'])!='');
$sql .= ' AND Second = "'.$_POST['Second'].'"';
if(($_POST['Third'])!='');
$sql .= ' AND Third = "'.$_POST['Third'].'"';
if(($_POST['Fourth'])!='');
$sql .= ' AND Fourth = "'.$_POST['Fourth'].'"';
或试试这个
$arr = $_POST;
$sql = " select * from table name where 1=1 "
foreach($arr as $key =>$ar){
if($ar!='') $sql .= ' AND '.$key.' = "'.$ar.'"';
}
输入名称和数据库字段名称必须相同...
答案 2 :(得分:0)
尝试使用此代码。您可以在foreach循环中实现搜索条件。
// HTML field names
$fields = array_flip(array("search1", "search2", "search3", "search4"));
$data = array_filter(array_intersect_key($_POST, $fields));
foreach ($data as $key => $val) {
// Here you can implement the sql search condtion
echo "$key => $val" . PHP_EOL;
}