skip to Main Content

Here is the code

<?php
$servername = "localhost";
$usrname   = "root";
$pwd = "";
$db = "test_db";
// connect to the database
$conn= mysqli_connect($servername, $usrname, $pwd,$db);
if (!$conn){
    die('connection failed' . mysqli_connect_error());
}
// Create database
$sql = "CREATE DATABASE IF NOT EXISTS test_db";
    if (mysqli_query($conn, $sql)) {
    echo "Database created successfully<br>";
} else {
  echo "Error creating database: " . mysqli_error($conn);
}
?>

I am not sure what is going on as I am sure i made no errors while typing. As it keeps showing me that there is an unknown database despite the fact i made a CREATE DATABASE statement.
I do not know if there is something else i need to do but by all measures the code should work.
It is supposed to echo the "Database created successfully" or the error message.

3

Answers


  1. <?php
    // Connect to MySQL
    $link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
    if (!$link) {
        die('Could not connect: ' . mysql_error());
    }
    
    // Make my_db the current database
    $db_selected = mysql_select_db('my_db', $link);
    
    if (!$db_selected) {
      // If we couldn't, then it either doesn't exist, or we can't see it.
      $sql = 'CREATE DATABASE my_db';
    
      if (mysql_query($sql, $link)) {
          echo "Database my_db created successfullyn";
      } else {
          echo 'Error creating database: ' . mysql_error() . "n";
      }
    }
    
    mysql_close($link);
    ?>
    

    Reference
    How do I create a database if it doesn’t exist, using PHP?

    Login or Signup to reply.
  2. $conn= mysqli_connect($servername, $usrname, $pwd,$db);

    You are trying to connect to a database that did not initially exist, so you get a fatal error.

    Try creating new database using try catch blocks

    try{
    $conn= mysqli_connect($servername, $usrname, $pwd,$db);
    }cath(Exception $e){
    //your code
    }
    
    Login or Signup to reply.
  3. `<?php
    $servername = "localhost";
    $usrname   = "root";
    $pwd = "";
    //$db = "test_db";
    // connect to the database
    $conn= mysqli_connect($servername, $usrname, $pwd);
    if (!$conn){
        die('connection failed' . mysqli_connect_error());
    }
    // Create database
    $sql = "CREATE DATABASE IF NOT EXISTS test_db";
        if (mysqli_query($conn, $sql)) {
        echo "Database created successfully<br>";
    } else {
      echo "Error creating database: " . mysqli_error($conn);
    }
    ?>`
    

    Your code is fine, You just have to remove $db from mysqli_connect().
    Because you are requesting to connect "test_db" to this database which already not exists.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search