Laravel 5.3中的SQL搜索查询错误

时间:2017-01-02 17:40:00

标签: php mysql sql laravel

我正在尝试构建搜索查询。我得到了以下错误,似乎sql的语法错误。

  

SQLSTATE [HY093]:参数号无效(SQL:从产品中选择*)   styles = Abstract,Abstract和subject =? )

为什么会出现此错误? 如何理解?

我的代码如下

if (isset($request->search)) { 

    //GET ALL INPUT FROM THE REQUEST       
    $query_strings = $request->all();            

    //PULL OUT ANY EMPTY FIELD FROM THE REQUEST
    $filtered_array = array_filter($request->all());

    //remove the last item
    array_pop($filtered_array);

    //BUILD A QUERY 
    $sql = array();
    $values = array();
    $x = 1;
    foreach ( $filtered_array as $key =>$value ) {           
        if($x < count($filtered_array)){
            $sql[]=" $key = ? and ";
            $values[] =" $value , ";
          } else { 
            $sql[]=" $key = ? ";
            $values[] ="  $value  ";
          }
            $x++;
     }

     $fields = join(' ',  $sql);
     $v = join(' ',$values);

     dd( \DB::select("select * from products where {$fields} ", [$v]));

}

2 个答案:

答案 0 :(得分:0)

如果您传递了一些值,则应添加?占位符:

\DB::select("select * from products where ?", [$value]));

答案 1 :(得分:0)

这有点紧张,我怀疑它会在第一次尝试时起作用。但我真的建议你尝试使用Laravel的query builder

此代码假定您将'products'表列名称作为GET或POST参数的名称以及要作为值查询的值传递。例如:

url.com?price=200&size=2

'price'和'size'是'products'表的列名。

代码:

// Check if request has 'search' parameter
if($request->has('search')) { 
  // $filtered_array now has all parameters that were passed to the controller
  $filtered_array = $request->all();

  // Start a query on table 'products'. Laravel style (more: https://laravel.com/docs/5.3/queries)
  $query = \DB::table('products');

  // For each parameter passed to the controller, we make "and where products.$key = $value" statement in the query
  foreach($filtered_array as $key => $value) {
    $query->where($key, '=', $value);
  }

  // Tell the query builder to get the results and save it to $results variable
  $results = $query->get();
}

这无疑会导致很多错误,因为任何人都可以发送任何内容作为GET / POST参数和查询(这会抛出该列不存在的SQL错误)。

您应该将$filtered_array = $request->all()更改为:

$filtered_array = $request->only(['id', 'price', 'size']);

这样,您只会在$ filtered_array中的 - &gt; only(数组)中存储您指定的参数,并忽略所有其他参数。因此,您应该将'id','price'和'size'替换为您要查询的'products'表的所有列。