SaidbakR
SaidbakR

Reputation: 13544

Laravel print DB sql after preparation

I have the following Laravel, 5.4, DB query, which generates an error:

$item = \DB::select("SELECT :id FROM :tab WHERE :id1 = :value",['id' => $parameters[3],'id1' => $parameters[3],'tab' => $parameters[2],'value' => $value]);

I need to know any way that allows me to printout the SQL statement after preparation and before execution. i.e after supplying the values of the placeholders to understand where is the error comes from.

I tried to use DB::connection()->enableQueryLog(); like the following:

\DB::connection()->enableQueryLog();
                $item = \DB::select("SELECT :id FROM :tab WHERE :id1 = :value",['id' => $parameters[3],'id1' => $parameters[3],'tab' => $parameters[2],'value' => $value]);
                dd(DB::getQueryLog());

It does not do any thing and sql error like:

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '? WHERE ? = ?' at line 1 (SQL: SELECT :id FROM :tab WHERE :id1 = :value)

Is there any method for the DB class that prints the statement with its values? i.e I need to see values instead of ?

Upvotes: 0

Views: 206

Answers (1)

Idob
Idob

Reputation: 1650

Try to post a dump of all the injected parameters to the query, it's probably an empty value or string value without quotes.

In general, I recommend you to work with Laravel's query builder, it's much simpler and its error is more indicative:

DB::table($parameters[2])
    ->select([$parameters[3]])
    ->where($parameters[3], $value)
    ->get();

Upvotes: 1

Related Questions