Reputation: 53
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.
Upvotes: 0
Views: 652
Reputation: 74217
"@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.
Upvotes: 2
Reputation: 360702
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.
Upvotes: 2