具有多个字段的 PHP 搜索

标签 php mysql search

我想使用带有多个字段搜索选项(例如姓名、学院、系、年份、国籍等)的 ajax 方法搜索数据。我有用于搜索的插入名称,其余字段比它进入 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";

    }

最佳答案

我终于找到了解决方案,感谢 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 "); 

     }

关于具有多个字段的 PHP 搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34256486/

相关文章:

algorithm - 如果第一个源节点出队后队列已经为空,广度优先搜索如何工作?

php - 用于获取业务评论的 Google plus API?

php - 如何在mysql中添加所有列的数据

mysql - 托管服务器上的 SQL 声明语句错误

mysql - MySQL 表的 'too many' 有多少行?

search - ElasticSearch更精确地匹配

php - 我正在尝试通过使用 php 调整图像大小将图像放入 div。但它不起作用

php - 使用 datagrid 、 flash 、 php 、 mysql 、 as3 显示数据库中的数据

javascript - 将来自多个 div 的代码转换为使用 Ajax

php - 使用数组 PHP 在 SQL 数据库中搜索