Skip to content
Advertisement

Fatal error: Uncaught mysqli_sql_exception: Unknown database ‘test_db’. I keep getting this error even though I programatically created the database

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.

Advertisement

Answer

`<?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.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement