1
$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

JValker
  • 374
  • 2
  • 14

1 Answers1

2

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";
ScaisEdge
  • 131,976
  • 10
  • 91
  • 107
  • 1
    I'm not the op, but backticks are not related to interpolation, it's a mysql thing. If the idea is to just remove the backticks, it should also work using double quotes and simply using the var without concatenation. – FirstOne Aug 09 '16 at 14:02
  • 1
    Since it looks like the op wants to dynamically create databases, some names might need backticks. Take a look at the first example from [this answer](http://stackoverflow.com/a/11321523/4577762) – FirstOne Aug 09 '16 at 14:02
  • @FirstOne The OP in this question don't want the backtikcs .. this is a simple solution ..there are many others .. solution .. you can post your if you like .. – ScaisEdge Aug 09 '16 at 14:05
  • 1
    They didn't say the name is getting backticks, it's getting quotes. Don't worry, I'm just pointing to a possible problem that could happen for not using backticks, specially since they _prefer not to hardcode the name_ (they might use a reserved word as db name) – FirstOne Aug 09 '16 at 14:07
  • @FirstOne thank for backtics / quote .. you are right .. anyway .. the way are essentially two . string concat on var with quote .. i have update the answer .. but .. in SQL every aspect is good for an encyclopedia.. – ScaisEdge Aug 09 '16 at 14:13
  • No problem, I just don't get how your answer is different from what the op seems to be trying already (the backticks) ^^ – FirstOne Aug 09 '16 at 14:15
  • 2
    Thanks for the answer, i was so busy scratching my head about the backticks i just didn't think using the string concat. Just a thing, @scaisEdge: the problem weren't the backticks in the query, but the quotes before and after the name in the database created. – JValker Aug 09 '16 at 15:17