0

I need to execute a query with DB::raw but it seems not working at all.
For some reason, Laravel does not execute the bindings, and the query fails. I have tried a lot of queries, events, and even a simple one doesn't work.

use Illuminate\Support\Facades\DB;

$query = 'select id from :my_table';

$results = DB::select(
    DB::raw($query),
    [
        'my_table' => 'advertisement__rentadvertisements',
    ]
);

dd($results);

Error

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 '?' at line 1 (SQL: select id from :my_table)

Any ideas?

Karl Hill
  • 12,937
  • 5
  • 58
  • 95
Christian Giupponi
  • 7,408
  • 11
  • 68
  • 113
  • 1
    Is there any reason why you're doing the above as a raw query and not using the methods on the query builder? – Rwd Jul 15 '19 at 07:43
  • That's not my final query, is just an example to show that event that easy query do not work – Christian Giupponi Jul 15 '19 at 07:56
  • If you can please don't just provide a simplified version of what you're trying to achieve as it means that you will usually not get the help/advise that you're after. Can you add the code you actually have to your question and also, if you can, just provide a quick overview of what you're trying to achieve and why :) – Rwd Jul 15 '19 at 07:59

4 Answers4

1

As mentioned in this post and this post, you can't just replace table names or columns.

Unless you've simplified your example and there is more going on than you've mentioned I would suggest just using the query builder:

DB::table('advertisement__rentadvertisements')->get('id')
Rwd
  • 34,180
  • 6
  • 64
  • 78
0

You have a syntax error, try remove the : in your $query and you should be fine, and also your statement needs an condition like select * from table_name where id = ?

draw134
  • 1,053
  • 4
  • 35
  • 84
0

Your binding syntax seems to be the issue. A semicolon is missing in your array:

$query = "select id from :my_table";

$results = DB::select(
    DB::raw($query),
    [
        ':my_table' => 'advertisement__rentadvertisements',
    ]
);

The error:

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 '?' at line 1 (SQL: select id from :my_table)"

is indicating that :my_table within your query is not replaced by advertisement__rentadvertisements.

Kévin Bibollet
  • 3,573
  • 1
  • 15
  • 33
0

You can't just replace table names or columns.

See more: https://laravel.com/docs/5.8/queries#selects

Change:

$query = 'select id from :my_table';

$results = DB::select(
    DB::raw($query),
    [
        'my_table' => 'advertisement__rentadvertisements',
    ]
);

to:

$results = DB::table('advertisement__rentadvertisements')->select('id')->get();

Hope it will help you.

Alex
  • 3,646
  • 1
  • 28
  • 25