I am trying to run a statement to create a database and a user, but it seems laravel continues to run weird queries. My code is as follows:
$res = DB::statement("CREATE DATABASE IF NOT EXISTS `?`", array($databaseName));
$res2 = DB::statement("CREATE USER '?'@'%' IDENTIFIED BY '?'", array($databaseName, $password));
return $res . " - " . $res2;
I would expect the database to be created and a "true" result, but the query still gives me a false response and no database is created. Trying to run a statement with the $databaseName variable inside the query in a "dirty way" works, so I think there's something wrong with prepared statements. Which would be the right way to do it?
Thank you! :)
Update: I've managed to do it, but it seems there are still SQL-injection issues because I'm still not able to use prepared statements. The first solution I've found is the following one:
$res = DB::statement("CREATE DATABASE IF NOT EXISTS `{$databaseName}`");
$res2 = DB::statement("CREATE USER '{$databaseName}'@'%' IDENTIFIED BY '{$password}'");
return $res . " - " . $res2;
Here's the code I've found that works:
DB::connection('database')->statement("CREATE USER '{$mysqlDatabaseName}'@'%' IDENTIFIED BY '{$mysqlUserPassword}'");
DB::connection('database')->statement("CREATE DATABASE IF NOT EXISTS `{$mysqlDatabaseName}`");
DB::connection('database')->statement("GRANT ALL PRIVILEGES ON `{$mysqlDatabaseName}`.* TO '{$mysqlDatabaseName}'@'%'");
However, before you run these queries, you must make sure you have no SQL-injection in your code.
Hope this will help somebody else! :)