0

I want to let users create a database. The query looks like this:

DB::statement( 'CREATE DATABASE mydbname' )

I need to use DB::statement instead of DB::select / DB::select / DB::update as the latter commands do not support the create statement.

I want to protect myself from SQL injection and unfortunately, the following two methods do not work with DB::statement:

DB::statement( 'CREATE DATABASE :DBNAME', [ 'DBNAME', 'mydbname' ] );
DB::statement( 'CREATE DATABASE ?', [ 'mydbname' ] );

So how could I protect the DB::statement method from SQL injection? If that's not possible how could I trigger the create query in a protected laravel way without using raw PHP-PDO?

manifestor
  • 1,352
  • 6
  • 19
  • 34
  • If you have to have a variable name for a table or column then your database is probably not set up very well. – GrumpyCrouton Apr 26 '18 at 18:50
  • What do you mean by that? How should a user else create a database? :) – manifestor Apr 26 '18 at 19:00
  • 4
    My question is why you're letting users create a database? – castis Apr 26 '18 at 19:06
  • Possible duplicate of [Can PHP PDO Statements accept the table or column name as parameter?](https://stackoverflow.com/questions/182287/can-php-pdo-statements-accept-the-table-or-column-name-as-parameter) – Mike Apr 26 '18 at 19:08
  • @castis: I'm writting a UI where they can manage their databases, what's so strange? :) – manifestor Apr 26 '18 at 19:18
  • Didn't say it was strange, just wondering is all. – castis Apr 26 '18 at 19:42
  • 1
    @chevallier Are the schemas for all databases equal, or can users create arbitrary tables? If they're all the same, simply add a `user_id` column to all tables and use a single database, giving access only to the values with that particular `user_id`. If not, the only thing I can think of is sanitizing all database and table names by limiting the characters in the variable to `[a-zA-z_]+` (see https://stackoverflow.com/questions/10993451/filter-var-using-filter-validate-regexp). – Mike Apr 26 '18 at 19:46
  • @Mike: Yes, that's the solution. Validate the request like this `'DatabaseName' => 'required|max:255|regex:/(^[A-Za-z0-9]+$)/'` and that should be safe enough, because there could be no quotes at all. Thanks. – manifestor Apr 26 '18 at 19:53

0 Answers0