简体   繁体   English

如何将参数传递给查询?

[英]How can I pass parameters to the query?

I use Laravel. 我用Laravel。 As you know, Laravel doesn't support UNION clause for the query. 如您所知,Laravel不支持查询的UNION子句。 So I have to write it as raw when I want to paging the whole results. 因此,当我想分页整个结果时,必须将其写为raw Something like this: 像这样:

$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
                      ');

As I said, I use Laravel, So how can I pass $q to the query in Laravel? 如我所说,我使用Laravel,那么如何在Laravel中将$q传递给查询呢? All I'm trying to do is making the query safe against SQL injections. 我要做的就是使查询对SQL注入安全。 That's why I'm trying to pass the parameters to the query rather that using them directly in the query. 这就是为什么我试图将参数传递给查询,而不是直接在查询中使用它们。


In pure PHP I can do that like this: 在纯PHP中,我可以这样做:

$st = $dbh->prepare('SELECT ... WHRER col LIKE %:q');
$st->bindParam(':q', $q, PDO::PARAM_INT);

I want something like this ^ in Laravel. 我想要类似Laravel中的^这样的内容。

Yes, there is union: https://laravel.com/docs/5.3/queries#unions 是的,这里有工会: https : //laravel.com/docs/5.3/queries#unions

I didn't test it out, but it should looks something like this: 我没有进行测试,但是它看起来应该像这样:

$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();

NOTE: 注意:

With union you won't be able to do paginate out of the box. 有了工会,您将无法直接进行paginate You will need to create the paginator object by yourself as shown here: Laravel - Union + Paginate at the same time? 您将需要自己创建分页器对象,如下所示: Laravel-并集+分页?

Your "pure PHP code" won't work either. 您的“纯PHP代码”也不起作用。 You have to respect SQL and PDO syntax 您必须尊重SQL和PDO语法

$st = $dbh->prepare('SELECT ... WHRER col LIKE :q');
$st->bindParam(':q', "%$q");

will do. 会做。

The same with Laravel: you have to define a placeholder in the query and then send it as a parameter 与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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM