Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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"

share|improve this question
    
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. –  Joshua Smock Oct 19 '13 at 9:03
3  
You should not use mysql_* functions! –  Guillaume Poussel Oct 19 '13 at 9:03
    
firstly change mysql_connect("localhost","root"); // you forgot to keep password –  user2092317 Oct 19 '13 at 9: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'. –  ScallioXTX Oct 19 '13 at 9:09
    
Actually yes, but I already figure it out to normalize it. Thanks –  XtraCode Oct 19 '13 at 9:20
add comment

2 Answers

up vote 6 down vote accepted

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

share|improve this answer
3  
@Downvoter: care to explain or suggest improvements? –  Amal Murali Oct 19 '13 at 9:04
2  
Also using backtick character instead of single quote, Not? –  hallaji Oct 19 '13 at 9:06
    
add else { test($db_usr) } in else part –  user2092317 Oct 19 '13 at 9:07
    
Single quote is a syntax error here. Should use backtick (ascii 96). To prevent SQL injection, he should replace backticks with double backticks in $db_usr (using str_replace). –  Federico Oct 19 '13 at 9:08
    
@hallaji: Derp. Fixed that :) –  Amal Murali Oct 19 '13 at 9:08
add comment

One more option:

function test()
    {
        $db_usr = mysql_real_escape_string($_POST["email"]);
        $query= "create database ".$db_usr ."";
        $result = mysql_query($query);
    }
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.