Escape raw SQL queries in Laravel 4

后端 未结 7 967
别那么骄傲
别那么骄傲 2020-12-15 16:23

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 als

相关标签:
7条回答
  • 2020-12-15 16:24

    You may also try this, (Read Documentation)

    $results = DB::select('SELECT * FROM users WHERE users.id = ?', array($userId));
    
    0 讨论(0)
  • 2020-12-15 16:27

    I'm using this in my helpers.php at Laravel 5:

    if ( ! function_exists('esc_sql'))
    {
        function esc_sql($string)
        {
            return app('db')->getPdo()->quote($string);
        }
    }
    

    Then I can use esc_sql function where I need to pergorm escaping for raw SQL queries.

    0 讨论(0)
  • 2020-12-15 16:29

    Two answers here, that I use, have less verbose solutions built into the DB facade.

    First, value quoting:

    // From linked answer
    DB::connection()->getPdo()->quote("string to quote");
    // In the DB facade
    DB::getPdo()->quote('string to quote');
    

    Second, identifier quoting (table and column names):

    // From linked answer
    DB::table('x')->getGrammar()->wrap('table.column');
    // In the DB facade
    DB::getQueryGrammar()->wrap('table.column');
    
    0 讨论(0)
  • 2020-12-15 16:31

    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.

    0 讨论(0)
  • 2020-12-15 16:35

    Here's a fuller example, showing how to escape both values and columns and extend Laravel's querybuilder:

    <?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]);
            });
        }
    }
    
    0 讨论(0)
  • 2020-12-15 16:37

    I found this question when looking for generic sql escaping in Laravel. What I actually needed though was table/column name escaping. So, for future reference:

    /**
     * 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);
    }
    
    0 讨论(0)
提交回复
热议问题