2017-01-02 57 views
1

我想構建一個搜索查詢。我得到以下錯誤,它似乎SQL語法錯誤。Laravel 5.3中的SQL搜索查詢錯誤

SQLSTATE [HY093]:無效的參數號(SQL:SELECT * FROM產品 地方風格=摘要,摘要和主題=?)

爲什麼發生這個錯誤? 如何弄清楚?

我的代碼如下

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

} 
+1

這是你正在談論的Laravel,你沒有使用它:(你也可以解釋一下你在哪裏得到一個錯誤,你會得到什麼錯誤。 – devk

回答

0

當你傳遞一些值,你應該添加?佔位符:

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

這是一個有點誇張的,我懷疑它會工作作爲是第一次嘗試。但我真的建議你嘗試使用Laravel的query builder

此代碼假設您傳遞'products'表列名作爲GET或POST參數的名稱以及要作爲值查詢的值。例如:

url.com?price=200&size=2 

其中「價格」和「尺寸」是「產品」表的列名稱。

代碼:

// 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並忽略所有其他人。因此,您應該用您希望查詢的'產品'表的所有列替換'id','price'和'size'。