Nyxynyx
Nyxynyx

Reputation: 63639

Laravel cannot use mysql_real_escape_string()

I get a database connection error when trying to use mysql_real_escape_string() within Laravel. Fluent queries work properly so I assume that the database has been configured correctly.

How should mysql_real_escape_string() be used from Laravel? I'm using it to escape the values in a SQL query that I need to build myself due to limitations of Fluent.

PHP Code that builds my own SQL query

    foreach($listings as $listing) {
        $listing = get_object_vars($listing);
        $query = 'INSERT IGNORE into archive ';
        $query .= '(' . implode(',', array_keys($listing)) . ') ';
        $query .= 'VALUES(' . implode(',', array_values( array_map('mysql_real_escape_string', $listing) )) . ')';
        DB::query($query);
    }

Error

mysql_real_escape_string() [function.mysql-real-escape-string]: 
Access denied for user 'nobody'@'localhost' (using password: NO)

Upvotes: 5

Views: 27151

Answers (4)

AMIB
AMIB

Reputation: 3430

use DB::connection()->getPdo()->quote() instead.

Upvotes: 19

Dirk
Dirk

Reputation: 2207

My solution for this:

  1. Create custom helpers file in app/lib/helpers.php
  2. Add this to autoload in composer.json:

    "files": [
        "app/lib/helpers.php"
    ],
    
  3. Add this function (found on php.net)

    if ( !function_exists('mysql_escape'))
    {
        function mysql_escape($inp)
        { 
            if(is_array($inp)) return array_map(__METHOD__, $inp);
    
            if(!empty($inp) && is_string($inp)) { 
                return str_replace(array('\\', "\0", "\n", "\r", "'", '"', "\x1a"), array('\\\\', '\\0', '\\n', '\\r', "\\'", '\\"', '\\Z'), $inp); 
            } 
    
            return $inp; 
        }
    }
    
  4. php artisan dump-autoload

Now you can use mysql_escape everywhere in your code.

Upvotes: 5

user254875486
user254875486

Reputation: 11240

mysql_real_escapes_string() uses a database link created with mysql_connect(), so it can only be used after you've called mysql_connect().

An important note about this (from the comments):

.. But shouldn't be used in environments where PDO is the database driver of choice. In fact, mysql_connect() shouldn't be used at all anymore. – Robin v. G.

Upvotes: 6

Sherlock
Sherlock

Reputation: 7597

Laravel uses PDO, so there's no escaping, just prepared statements. See the Laravel manual on databases.

Upvotes: 3

Related Questions