[英]How can I pass parameters to the query?
我用Laravel。 如您所知,Laravel不支持查詢的UNION
子句。 因此,當我想分頁整個結果時,必須將其寫為raw
。 像這樣:
$results = DB::select('SELECT id, title, description, imgPath
FROM news n
WHERE n.title LIKE %$q OR n.description LIKE %$q
UNION ALL
SELECT id, title, description, imgPath
FROM productions p
WHERE p.title LIKE %$q OR p.description LIKE %$q
');
如我所說,我使用Laravel,那么如何在Laravel中將$q
傳遞給查詢呢? 我要做的就是使查詢對SQL注入安全。 這就是為什么我試圖將參數傳遞給查詢,而不是直接在查詢中使用它們。
在純PHP中,我可以這樣做:
$st = $dbh->prepare('SELECT ... WHRER col LIKE %:q');
$st->bindParam(':q', $q, PDO::PARAM_INT);
我想要類似Laravel中的^這樣的內容。
是的,這里有工會: https : //laravel.com/docs/5.3/queries#unions
我沒有進行測試,但是它看起來應該像這樣:
$first = DB::table('news')
->select(['id', 'title', 'description', 'imgPath'])
->where(function($query) use ($q) {
$query->where('title', 'like', "%$q")
->orWhere('description', 'like', "%$q");
});
$result = DB::table('productions')
->select(['id', 'title', 'description', 'imgPath'])
->where(function($query) use ($q) {
$query->where('title', 'like', "%$q")
->orWhere('description', 'like', "%$q");
})
->unionAll($first)
->get();
注意:
有了工會,您將無法直接進行paginate
。 您將需要自己創建分頁器對象,如下所示: Laravel-並集+分頁?
您的“純PHP代碼”也不起作用。 您必須尊重SQL和PDO語法
$st = $dbh->prepare('SELECT ... WHRER col LIKE :q');
$st->bindParam(':q', "%$q");
會做。
與Laravel相同:您必須在查詢中定義一個占位符,然后將其作為參數發送
$sql = 'SELECT * FROM news WHERE title LIKE :q OR description LIKE :q';
$results = DB::select($sql, ['q' => "%$q"]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.