在 Laravel 4 中转义原始 SQL 查询

2021-12-26 00:00:00 php mysql laravel pdo laravel-4

如何在 Laravel 4 中转义传递给原始查询的参数?我期待像 DB::escape()(它从 Laravel 3 中敲响钟声)并且还尝试了 DB::quote()(我认为可以通过PDO 对象)

How does one go about escaping parameters passed to a raw query in Laravel 4? I expected something like DB::escape() (which rings a bell from Laravel 3) and also attempted DB::quote() (which I thought could be available through the PDO object)

$query = DB::select("SELECT * FROM users WHERE users.id = " . DB::escape($userId));

我们不能使用带有占位符的 select 方法,因为上面只是我们试图实现的一个简化示例.我们有一个大型自定义查询,其中包含一些无法实现的嵌套选择查询适应查询构建器.

We can't use the select method with placeholders as the above is just a simplified example of what we are trying to achieve. We have a large custom query with a few nested select queries that cannot be adapted to the query builder.

在插入 Laravel 4 之前转义某些内容的最佳方法是什么?

What is the best approach to escaping something prior to inserting in Laravel 4?

我刚刚发现您可以通过这种方式访问​​ PDO 对象并在其上使用引用函数.这仍然是最好的方法,还是有更简单的方法来访问这个功能?

I've just discovered that you can access the PDO object and use the quote function on it this way. Is this still the best approach, or is there an easier way to access this function?

DB::connection()->getPdo()->quote("string to quote");

推荐答案

您可以通过 DB 外观以这种方式引用您的字符串.

You can quote your strings this way, through the DB facade.

DB::connection()->getPdo()->quote("string to quote");

当我发现它时,我确实把这个答案放在了我的问题中,但是我现在把它作为一个实际的答案,以便其他人更容易找到.

I did put this answer in my question when I discovered it, however I've now put it in as an actual answer to make it easier for others to find.

相关文章