[英]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.