doujiyan0971 2015-12-13 21:19
浏览 342
已采纳

PHP搜索多个字段

I want to search data using ajax method with multiple fields search option (e.g. name, college, department, year, nationality e.t.c ). I have insert name for searching and rest of fields are empty than it went to foreach loop but this if (isset($_GET[$field]) && !empty($_GET['$field'])) condition not successful and went to else loop

  $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条回答 默认 最新

  • dongyuqi3808 2015-12-15 11:27
    关注

    At last i have found the solution and thanks to cFreed and other who help me. My main concern is that if user want to search with one field only or more than 1 field in that case below answer is helpful for me and may be also for someone:

    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 "); 
    
         }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型