2

I've got a string that looks like this :

use Illuminate\Database\Capsule\Manager as DB;

DB::select("SELECT id FROM table_?", [$var]);

So the query would look like SELECT id FROM table_users.

The problem is that I get a syntax error :

You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '?' at line 1

Why won't eloquent (or PDO in general) replace a ? attached to a string?

Alexandre Elshobokshy
  • 10,720
  • 6
  • 27
  • 57

1 Answers1

3

PDO doesn't just replace ? with other strings. It performs a semantic parsing of the query, constructs an execution plan, and then executes it with the values you bind to it. Without the table name, you cannot build an execution plan. Thus, you can't bind arbitrary strings that are part of table names like that. You'll have to resort to string concatenation instead:

DB::select("SELECT id FROM table_" . "users");

or, since you already have all the strings as literals, just do this yourself:

DB::select("SELECT id FROM table_users");
Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • I'm sorry, it was just an example, but the parameter isn't a string literal but a variable, I just made it a string in the example in the OP to simplify the question. And when you say *you can't*, the question is why? Also I'm not looking for another way of doing it, the question really is why can't we do it this way. As far as I know, the array replaces each `?` in order by the values of the array. In this case, when the `?` is attached to a string it ignores it. – Alexandre Elshobokshy Mar 15 '19 at 11:12
  • @GiveMeFreedomOrGiveMeFire PDO doesn't just replace `?` with other strings. It performs a semantic parsing of the query, constructs an execution plan, and then executes it with the values you bind to it. Without the table name, you cannot build an execution plan. – Mureinik Mar 15 '19 at 11:24
  • Please add that comment of yours to the answer, thanks! – Alexandre Elshobokshy Mar 15 '19 at 11:24