5

Can I have Eloquent ORM run a query without using prepared statements? Or do I have to use whereRaw()?

I need to use a raw query because I'm trying to interact with InfiniDB, which lacks support for prepared statements from PHP. At any rate, all queries will be using internally generated data, not user input so it should not be a security issue.

2 Answers 2

1

For anything other than SELECT you can use unprepared()

DB::unprepared($sql);

For an unprepared SELECT you can use plain PDO query() by getting access to active PDO connection through getPdo()

$pdo = DB::getPdo();
$query = $pdo->query($sql);
$result = $query->fetchAll();
Sign up to request clarification or add additional context in comments.

2 Comments

So essentially there's no easy way to do what I need to do - I'll just have to manually write out the query?
@peterm Maybe you can help me. Look at this : stackoverflow.com/questions/51838922/…
1

There's an easy way to do it. In the file config/database.php you can specify options for php PDO like so:

'mysql_unprepared' => [
        'driver' => 'mysql',
        'host' => env('DB_HOST', '127.0.0.1'),
        'port' => env('DB_PROXY_PORT', '6033'),
        'username' => env('DB_CACHED_USERNAME', 'forge'),
        'password' => env('DB_CACHED_PASSWORD', ''),
        'database' => env('DB_DATABASE', 'forge'),
        'unix_socket' => env('DB_SOCKET', ''),
        'charset' => 'utf8mb4',
        'collation' => 'utf8mb4_unicode_ci',
        'prefix' => '',
        'prefix_indexes' => true,
        'strict' => true,
        'engine' => null,
        'options' => extension_loaded('pdo_mysql') ? [
            PDO::ATTR_EMULATE_PREPARES => true,
        ] : [],
        'modes'  => [
            'ONLY_FULL_GROUP_BY',
            'STRICT_TRANS_TABLES',
            'NO_ZERO_IN_DATE',
            'NO_ZERO_DATE',
            'ERROR_FOR_DIVISION_BY_ZERO',
            'NO_ENGINE_SUBSTITUTION',
        ],
    ],

As you can see, there is an option PDO::ATTR_EMULATE_PREPARES which, when set to true, will do a prepare-like action on application level and send the query unprepared instead. I didn't figure PDO had this option until I had already created an extension for Laravel's mysql driver just to intercept select queries and do unprepared mysqli queries instead so that ProxySql could cache them.

So this answer could have been a lot more complicated. Cheers.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.