Reputation: 693
I'm trying to create a database with CREATE DATABASE command, but instead it gives me an error. this is my code:
$db_usr = mysql_real_escape_string($_POST["email"]);
$con=mysql_connect("localhost","root");
if (! $con)
{
die('Could not connect: ' . mysql_error());
}
else
{
test();
}
function test()
{
$sql = "CREATE DATABASE '$db_usr'";
mysql_query($sql);
}
It always returns "Undefined variable"
Upvotes: 0
Views: 128
Reputation: 349
One more option:
function test()
{
$db_usr = mysql_real_escape_string($_POST["email"]);
$query= "create database ".$db_usr ."";
$result = mysql_query($query);
}
Upvotes: 0
Reputation: 76666
The $db_user
variable isn't accessible inside your function scope and that's the reason why you're getting that error.
If you want the variable to be used inside your function, then pass it as a function parameter, like so:
function test($db_usr)
{
$sql = "CREATE DATABASE `$db_usr`";
mysql_query($sql);
}
If this involves user input, then your database query is vulnerable to SQL injection. You should always validate user input (recommended way is to use MySQLi or PDO with parameterized queries).
Upvotes: 6