How to create a new database (with prepared statements)?

periloso posted 3 years ago

Hello, I am trying to run a statement to create a database and an user, but it seems laravel continues to run weird queries. My code is as follows:

$res = DB::connection('mysql')->statement("CREATE DATABASE IF NOT EXISTS `?`", array($databaseName));
$res2 = DB::connection('mysql')->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 $mysqlDatabaseName 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 and regards from Italy, Alessio Periloso

periloso replied 3 years ago

Okay, it seems I've found a solution. Can I do it this way?

$res = DB::connection('mysql')->statement("CREATE DATABASE IF NOT EXISTS `{$mysqlDatabaseName}`");
$res2 = DB::connection('mysql')->statement("CREATE USER '{$mysqlDatabaseName}'@'%' IDENTIFIED BY '{$mysqlPassword}');

Or would I have SQL-injection problems?

Thanks again, Alessio Periloso

lionslair replied 6 days ago

How would I do this if I am wanting to use sqlite in testing?

Sign in to participate in this thread!

We'd like to thank these amazing companies for supporting us