我想使用ajax方法搜索数据,使用多个字段搜索选项(例如姓名、学院、系、年份、国籍等)。我有用于搜索的插入名称,其余的字段都是空的,但如果(isset($_GET$field) &!空($_GET‘$field’)条件不成功,则转到else循环。
$fields = array(
'name' => TRUE,
'gender' => TRUE,
'colf' => TRUE,
'deptf' => TRUE,
'natf' => TRUE,
'fstatusf' => TRUE,
'fyearf' => TRUE
);
foreach ($fields as $field => $like) {
if (isset($_GET[$field]) && !empty($_GET['$field'])) {
$value = $_GET[$field];
$search[] = $field . ( $like ? ('LIKE "%' . $value . '%"') : ('="' . $value . '"') );
}
}
if ($search) {
$sql = 'SELECT * FROM fmaf WHERE ' . implode(' or ' . $search);
}
else{
$sql="SELECT * FROM fmaf";
}发布于 2015-12-15 11:27:57
最后,我找到了解决方案,感谢cFreed和其他帮助我的人。我主要担心的是,如果用户只想搜索一个字段,或者在这种情况下搜索超过一个字段,那么答案对我很有帮助,而且可能也会对某些人有帮助:
if (empty($_GET['name']) && empty($_GET['gender']) && empty($_GET['colf']) && empty($_GET['deptf']) && empty($_GET['natf']) && empty($_GET['fstatusf']) && empty($_GET['fyearf']))
{
$sql="select * from fmaf ";
}
else
{
$wheres = array();
$sql = "select * from fmaf where ";
if (isset($_GET['name']) and !empty($_GET['name']))
{
$wheres[] = "name like '%{$_GET['name']}%' ";
}
if (isset($_GET['gender']) and !empty($_GET['gender']))
{
$wheres[] = "gender = '{$_GET['gender']}'";
}
if (isset($_GET['colf']) and !empty($_GET['colf']))
{
$wheres[] = "college = '{$_GET['colf']}' ";
}
if (isset($_GET['deptf']) and !empty($_GET['deptf']))
{
$wheres[] = "department = '{$_GET['deptf']}' ";
}
if (isset($_GET['natf']) and !empty($_GET['natf']))
{
$wheres[] = "nationality = '{$_GET['natf']}' ";
}
if (isset($_GET['fstatusf']) and !empty($_GET['fstatusf']))
{
$wheres[] = "finalstatus = '{$_GET['fstatusf']}' ";
}
if (isset($_GET['fyearf']) and !empty($_GET['fyearf']))
{
$wheres[] = "fyear = '{$_GET['fyearf']}' ";
}
foreach ( $wheres as $where )
{
$sql .= $where . ' AND '; // you may want to make this an OR
}
$sql=rtrim($sql, "AND ");
}发布于 2015-12-13 21:28:10
您需要根据请求构建查询。一个玩具例子是:
$sql = "select * from student where 1 = 1".(isset($name)?" AND name like '%$name%":"").(isset($country)?" AND country = '$country'":"").";";发布于 2015-12-13 21:38:39
你可以使用一种简单的方法,能够面对任何情况,就像这样:
// define searchable fields, with option for LIKE|EQUAL (TRUE|FALSE)
$fields = [
'name' => TRUE,
'country' => TRUE,
'address' => TRUE,
'gender' => FALSE,
'state' => FALSE
];
foreach ($fields as $field => $like) {
if (isset($_GET[$field]) AND !empty($_GET['$field'])) {
$value = $_GET[$field];
// prepare WHERE condition item, depending on LIKE option
$search[] = $field . (
$like ? ('LIKE "%' . $value . '%"') : ('="' . $value . '"')
);
}
}
if ($search) {
$sql = 'SELECT * FROM student WHERE ' . implode(' AND ' . $search);
}https://stackoverflow.com/questions/34256486
复制相似问题