0

I wish to create a database in mysql via php but I get access denied error. This is the code:

<form action = "createdb.php" method = "post">
<label for = "dbname">database name to be created</label><br>
<input type = "text" name = "dbname" /><br>
<input type = "submit" name = "submit" value = "submit"/>
</form>

<?php 
if(isset($_POST['submit'])){
$server = 'localhost';
$uname = 'root';
$pass = 'jooko';
$dbname = $_POST['dbname'];
$createdb = "CREATE DATABASE `$dbname`";
$connect = mysql_connect(`$server`,`$uname`,`$pass`);
//$queryuse = "USE '$dbname'";

$result = mysql_query($createdb, $connect);
if(!$result){echo mysql_error();}
?>

Any help will be appreciated. Thank you.

brown.cn
  • 151
  • 1
  • 9
  • 'Access Denied' - either your username/password combination is wrong, or you don't have permission to perform the query. Assuming the latter (from the placement of your single error check) you don't have permission to create a database. On a shared hosting system this is quite common. Database creation is usually done manually via a control panel of some sort. –  Apr 27 '14 at 00:17
  • Is your username/password combo correct? Has the `root` user been stripped of its `CREATE DATABASE` capabilities? – esqew Apr 27 '14 at 00:17
  • root has all available privileges enabled – brown.cn Apr 27 '14 at 00:29

2 Answers2

0

Deprecation notice: Don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.

Also the backticks in your function arguments will cause problems. This is how todo it with PDO.

<form action = "createdb.php" method = "post">
    <label for = "dbname">database name to be created</label><br>
    <input type = "text" name = "dbname" /><br>
    <input type = "submit" name = "submit" value = "submit"/>
</form>

<?php 
if($_SERVER['REQUEST_METHOD'] == 'POST'){
    $server = 'localhost';
    $uname = 'root';
    $pass = 'jooko';
    $dbname = $_POST['dbname'];

    try {
        $pdo = new PDO("mysql:host=".$server.";", $uname, $pass);
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        $dbname = "`".str_replace("`", "``", $dbname)."`";
        $pdo->query("CREATE DATABASE IF NOT EXISTS ".$dbname);

        echo 'Database created.';
    }catch (Exception $e){
        echo $e->getMessage();
    }
}
?>

If you are still having access denied problems then check the root password is correct.

Zoe
  • 27,060
  • 21
  • 118
  • 148
Lawrence Cherone
  • 46,049
  • 7
  • 62
  • 106
0

I did it. The problem was the back quotes in the $connect variable for the login data. Had to remove the back quotes for the $uname and $pass ...have no clue why it had to be that way but it works. Thanks though.

brown.cn
  • 151
  • 1
  • 9