使用多个字段搜索MySQL表

时间:2015-09-06 10:12:20

标签: php mysql laravel request laravel-5

我有这个HTML表单,它有很多字段,有人可以使用它来使用多个条件从MySQL表中查询数据。表单包含选择框,文本框和复选框以及日期输入。

search

我有这个无效的功能

public function search(Request $request)
    {

        // loop through the defined fields
        foreach($this->fields as $field){
            // if the field is set and not empty
            if(is_array($request->get($field))){
                foreach ($request->get($field) as $value) {
                    $this->conditions[] = "`$field` = '" . $value . "'";
                }
            } else {
                 if(isset($_POST[$field]) && $request->get($field) != '') {

                    $data = $request->get($field);

                    if($field == 'bf_ref_no'){
                        $data = is_numeric( substr($request->get($field), 0, 2) )  ? 'BF'.$request->get($field)  : $request->get($field) ;
                    }

                    $this->conditions[] = "`$field` = '" . $data . "'";
                }
            }

        }

        // builds the query
        $query = "SELECT invoices.id as inv_id, invoices.created_at as inv_date, invoices.amount_paid, invoices.amount, csv_data_final.* FROM csv_data_final 
        LEFT JOIN invoices ON invoices.parent_id = csv_data_final.id ";
        // if there are conditions defined
        if(count($this->conditions) > 0) {
            // append the conditions
            $query .= "WHERE " . implode (' AND ', $this->conditions); // you can change to 'OR', but I suggest to apply the filters cumulative
        }

        $results = DB::select( $query );

        $borders = DB::table('borders')->orderBy('id', 'DESC')->get();

        return view('track.track-withdata', compact('results', 'borders'));

    }

此代码不适用于使用BETWEEN关键字的日期。

0 个答案:

没有答案