0

I need to create separate database for different users.The database name would be that user's name. I tried the following

$user=preg_replace('#[^A-Za-z0-9]#','',$_GET['u']); 

if(! $connect_dude )
 {
  die('Could not connect: ' . mysqli_error());
 }
else{
  echo 'Connected successfully<br />';
 }

$sql2 = "CREATE DATABASE '.$user.'";
$query2=mysqli_query($connect_dude,$sql2);
if($query2===TRUE){
 echo "Database created";
}
else{
 echo "Not created";
}

but it doesn't work.

If I use static name for database,that works.That create database. But I need different database name for different user.

Please help.

Thanks in advance.

11
  • 3
    Do you really need to create an entire new database for each user? Normally you'd just have a users table and reference it with foreign keys. Commented Sep 25, 2014 at 20:31
  • 1
    Why are you creating a different database per user Commented Sep 25, 2014 at 20:32
  • Remove the quotes and dots '.$user.' and use backticks ` around that variable. Commented Sep 25, 2014 at 20:34
  • @Fred-ii-You are the savior.You are the best.You helped mw with my last ques. too.It worked.Please put that on answer sec.And,I would choose this as answer Commented Sep 25, 2014 at 20:38
  • @Quentin Yes I do.Because I need lots of table on that user's database Commented Sep 25, 2014 at 20:41

2 Answers 2

2

"@Fred-ii-You are the savior.You are the best.You helped mw with my last ques. too.It worked.Please put that on answer sec.And,I would choose this as answer"

As per OP's request:

Remove the quotes and dots '.$user.' and use backticks around the variable.

$sql2 = "CREATE DATABASE `$user`";

Tables and column identifiers require either no quotes or backticks.

Although it is best using backticks, should the variable contain a reserved keyword, a space, a hyphen or any other character(s) that SQL may not agree with.


Add or die(mysqli_error($connect_dude)) to mysqli_query()

which would have signaled the error.

Sign up to request clarification or add additional context in comments.

Comments

2

If $user is foo, then you're trying to create a database named .foo.

Try any of these instead:

$sql2 = "CREATE DATABASE '$user'";
$sql2 = "CREATE DATABASE '{$user}'";
$sql2 = "CREATE DATABASE '" . $user . "'";

And note that even though you're filtering $_GET['u'] to be alpha-numeric only, you can STILL cause SQL syntax errors, e.g. consider someone passing in u=table or 01234. Neither of those are valid DB (or table, or field) names.

2 Comments

And use backticks instead of single quotation marks
none of them worked.but using $user it worked,as suggested by Fred-ii.Thanks though

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.