-2

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
  • You can not create database when you connection is null or setup is failed. Create database using shell or connect to other database to create MySQL connection. Commented Nov 25, 2022 at 3:51
  • 1
    Don't connect with a DB parameter mysqli_connect($servername,$usrname,$pwd), then use mysqli_select_db($db) once the DB exists, assuming your credential has permission to call CREATE DATABASE Commented Nov 25, 2022 at 3:54
  • What have you tried to resolve the problem? Where are you stuck? Commented Nov 25, 2022 at 5:09

2 Answers 2

0
<?php
$servername = "localhost";
$usrname   = "root";
$pwd = "";
$db = "test_db";

// connect to the database
$conn= mysqli_connect($servername, $usrname, $pwd);

// Create database
$sql = "CREATE DATABASE $db";
mysqli_query($conn, $sql);

Your code is fine, You just have to remove $db from mysqli_connect(). Because you are trying to use a database "test_db" which doesn't exist yet.

Sign up to request clarification or add additional context in comments.

Comments

-3

$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
}

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.