Vkfan Vkfan - 3 months ago 10
MySQL Question

Creating a new database with php/PDO using a variable as the database name

$db_name = 'myDbName';
CREATE DATABASE IF NOT EXISTS `$db_name` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;


The moment these 2 instructions are executed, the database is created, but its name is 'myDbName', quotes included.

If i remove the quotes in the first line, i'll get a PHP error, and if i remove the
from the second one, i'll get a mySql error.

Is there a way to remove them/create a database with the correct name without directly accessing the DBMS?

I'd really prefer not to hardcode the name in the second line

Thanks in advance for the answers

Answer

You can use string concat and remove backticks

"CREATE DATABASE IF NOT EXISTS  " . $db_name . " DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci";

you can also avoid concat and using var inside quote (this could be useful if you need backticks for allow reserved word)

"CREATE DATABASE IF NOT EXISTS  '$db_name' DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci";
Comments