如何在
Laravel 4中转义传递给原始查询的参数?我期待类似 DB::escape()
的东西(它敲响了 Laravel 3 的钟声),并且还尝试了DB::quote()
(我认为可以通过 PDO 对象获得)
$query = DB::select("SELECT * FROM users WHERE users.id = " . DB::escape($userId));
我们不能将 select 方法与占位符一起使用,因为上面只是我们试图实现的目标的简化示例。我们有一个大型自定义查询,其中包含一些无法适应查询生成器的嵌套选择查询。
在插入 Laravel 4 之前转义某些东西的最佳方法是什么?
编辑:
我刚刚发现您可以访问 PDO 对象并以这种方式在其上使用报价函数。这仍然是最好的方法,还是有更简单的方法来访问此功能?
DB::connection()->getPdo()->quote("string to quote");
你可以通过这种方式引用你的字符串,通过DB
的外观。
DB::connection()->getPdo()->quote("string to quote");
当我发现它时,我确实把这个答案放在我的问题中,但是我现在把它作为一个实际的答案,以便其他人更容易找到。
$value = Input::get("userID");
$results = DB::select( DB::raw("SELECT * FROM users WHERE users.id = :value"), array(
'value' => $value,
));
更多详情 这里
你也可以试试这个,(阅读文档)
$results = DB::select('SELECT * FROM users WHERE users.id = ?', array($userId));
我在这里使用的两个答案在DB
外观中内置了不那么冗长的解决方案。
一、价值引用:
// From linked answer
DB::connection()->getPdo()->quote("string to quote");
// In the DB facade
DB::getPdo()->quote('string to quote');
其次,标识符引用(表名和列名):
// From linked answer
DB::table('x')->getGrammar()->wrap('table.column');
// In the DB facade
DB::getQueryGrammar()->wrap('table.column');
我在 Larawel 中寻找通用 sql 转义时发现了这个问题。我实际需要的是表/列名称转义。因此,供将来参考:
/**
* Quotes database identifier, e.g. table name or column name.
* For instance:
* tablename -> `tablename`
* @param string $field
* @return string
*/
function db_quote_identifier($field) {
static $grammar = false;
if (!$grammar) {
$grammar = DB::table('x')->getGrammar(); // The table name doesn't matter.
}
return $grammar->wrap($field);
}
我在 Laravel 5 的helpers.php
中使用它:
if ( ! function_exists('esc_sql'))
{
function esc_sql($string)
{
return app('db')->getPdo()->quote($string);
}
}
然后,我可以在需要对原始SQL查询进行转义的地方使用esc_sql
函数。
下面是一个更完整的示例,展示了如何转义值和列并扩展 Laravel 的查询生成器:
<?php
namespace App'Providers;
use Illuminate'Database'Query'Builder;
use Illuminate'Support'ServiceProvider;
class DatabaseQueryBuilderMacroProvider extends ServiceProvider {
public function register() {
Builder::macro('whereInSet', function($columnName, $value) {
/** @var 'Illuminate'Database'Query'Grammars'Grammar $grammar */
$grammar = $this->getGrammar();
return $this->whereRaw('FIND_IN_SET(?,' . $grammar->wrap($columnName) . ')', [$value]);
});
}
}
PHP Heredoc
<?php
use Illuminate'Support'Facades'DB;
$sql = <<<SQL
WITH table1 AS(SELECT...
SQL;
$parameters = [1,2,3,...]
$table = DB::select($sql, $parameters);