laravel 5搜索多个字段

时间:2016-06-19 18:25:32

标签: php mysql search laravel-5.2

我在多个搜索字段中有一个PHP代码,但我不知道如何在laravel中使用此功能

laravel中的mysql语法在简单的php中不一样,所以我可以编译它。

if(isset($_GET['submit'])) {
// define the list of fields
      if(isset($_GET['debit']) && !empty($_GET['debit'])) {

    $_GET['valeur'] = - $_GET['debit'];
  }
  else
  {
    if(isset($_GET['credit']) && !empty($_GET['credit']))
    {
        $_GET['valeur'] = $_GET['credit'];
    }
  }
    $fields = array('id_type', 'date_operation', 'date_valeur', 'numero','tiers','description','valeur');
    $conditions = array();


// builds the query
$query = "SELECT * FROM ecritures WHERE id_compte ='" . $iduser . "' ";


// loop through the defined fields
foreach($fields as $field){
    // if the field is set and not empty
    if(isset($_GET[$field]) && !empty($_GET[$field])) {
        // create a new condition while escaping the value inputed by the user (SQL Injection)
        $conditions[] = "$field LIKE '%" . mysqli_real_escape_string($co, $_GET[$field]) . "%'";
        }
    }


// if there are conditions defined
if(count($conditions) > 0) {
    // append the conditions
    $query .= " AND " . implode (' AND ', $conditions); // you can change to 'OR', but I suggest to apply the filters cumulative
}}

1 个答案:

答案 0 :(得分:2)

Laravel中的查询构建器使得这种查询比像代码手动创建SQL查询更容易。

所以这段代码应该适合你:

$q = DB::table('ecritures ')->where('id_compte', $iduser);


// loop through the defined fields
foreach($fields as $field){
    // if the field is set and not empty
    if(isset($_GET[$field]) && !empty($_GET[$field])) {
        // create a new condition
        $q = $q->where($field, 'LIKE', '%' . $_GET[$field] . '%');
    }
}

$result = $q->get();

foreach ($result as $row) {
    echo $row->column_name;
}

我也省略了escape函数,因为Laravel会为你处理这个问题。