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

3
  • Just to make sure, how do you know the name is 'myDbName' with the quotes? Commented Aug 9, 2016 at 13:57
  • Try echoing the query before running it. Check the page's source to see what's outputted too. Commented Aug 9, 2016 at 14:16
  • @FirstOne, i checked it from the DBMS.<br>But i don't want the end user to have to access it. Commented Aug 9, 2016 at 15:10

1 Answer 1

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";
Sign up to request clarification or add additional context in comments.

7 Comments

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.
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
@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 ..
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)
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.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.