PHP搜索多个字段

时间:2015-12-13 21:19:04

标签: php mysql search

我想使用带有多个字段搜索选项的ajax方法搜索数据(例如姓名,学院,部门,年份,国籍e.t.c)。我有搜索的插入名称,其余的字段是空的,而不是它转到foreach循环但是这个if(isset($ _ GET [$ field])&&!empty($ _ GET [' $ field' ]))条件不成功并转到其他循环

  $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";

    }

3 个答案:

答案 0 :(得分:0)

您需要根据请求构建查询。 一个玩具的例子就是:

$sql = "select * from student where 1 = 1".(isset($name)?" AND name like '%$name%":"").(isset($country)?" AND country = '$country'":"").";";

答案 1 :(得分:0)

您可以使用一种简单的方法,能够面对任何情况,例如:

// 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);
}

答案 2 :(得分:0)

最后我找到了解决方案并感谢cFreed和其他帮助我的人。我主要担心的是,如果用户想要只搜索一个字段或者在这种情况下搜索超过1个字段,则回答对我有用,也可能对某人有用:

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 "); 

     }