0

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"

Vahid Hallaji
  • 7,159
  • 5
  • 42
  • 51
conquistador
  • 673
  • 3
  • 11
  • 35
  • Don't use `mysql_query`, since it's deprecated. If you can't/aren't going to use PDO, use the `mysqli` library. Please see [the PHP docs](http://php.net/manual/en/book.mysqli.php). – josh Oct 19 '13 at 09:03
  • 3
    You [**should not use mysql_* functions**](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php)! – Guillaume Poussel Oct 19 '13 at 09:03
  • firstly change `mysql_connect("localhost","root");` // you forgot to keep password – user2092317 Oct 19 '13 at 09:04
  • You are creating one database per user? Are you sure this is the best way to go? It's probably a good idea to look up 'database normalisation'. – rpkamp Oct 19 '13 at 09:09
  • Actually yes, but I already figure it out to normalize it. Thanks – conquistador Oct 19 '13 at 09:20

2 Answers2

6

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

Amal Murali
  • 75,622
  • 18
  • 128
  • 150
0

One more option:

function test()
    {
        $db_usr = mysql_real_escape_string($_POST["email"]);
        $query= "create database ".$db_usr ."";
        $result = mysql_query($query);
    }
Sandesh
  • 349
  • 2
  • 8