【问题标题】:SQL Search query error in Laravel 5.3Laravel 5.3 中的 SQL 搜索查询错误
【发布时间】:2017-05-16 19:27:09
【问题描述】:

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

SQLSTATE[HY093]: 参数号无效(SQL: select * from products 其中样式 = 摘要、摘要和主题 = ? )

为什么会出现这个错误? 怎么弄出来的?

我的代码如下

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]));

}

【问题讨论】:

  • 你说的是 Laravel,但你没有使用它 :( 你也能解释一下你在哪里出错以及你得到了什么错误。

标签: php mysql sql laravel


【解决方案1】:

当你传递一些值时,你应该添加?占位符:

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

【讨论】:

    【解决方案2】:

    这有点牵强,我怀疑它在第一次尝试时会起作用。但我真的建议你尝试使用 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-&gt;all() 更改为:

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

    这样您将只存储您在 $filtered_array 中的 ->only(array) 中指定的参数,而忽略所有其他参数。所以你应该用你想要查询的'products'表的所有列替换'id'、'price'和'size'。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-27
      • 1970-01-01
      • 1970-01-01
      • 2017-06-24
      • 2016-12-31
      • 2016-12-31
      • 1970-01-01
      • 2017-07-20
      相关资源
      最近更新 更多