I am trying to create a database using mysqli if the database name doesn't exist using the following code:
<?php
$link = mysqli_connect("localhost", "root", "", "php1") ;
if(mysqli_connect_errno()){
echo mysqli_connect_error();
$query = "CREATE DATABASE php1";
if(mysqli_query($link, $query)){
echo "Success";
} else {
echo "Failure";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<a href="signup.php"><button type="button">Sign Up!</button></a>
<a href="login.php"><button type="button">Log In</button></a>
</body>
</html>
The code checks the db & it doesn't exists. Next I want to create the database if it does not exist but I am getting the following error always:
Warning: mysqli_connect(): (HY000/1049): Unknown database 'php1' in E:\xampp\htdocs\PhpProject1\index.php on line 3
Unknown database 'php1'
Warning: mysqli_query() expects parameter 1 to be mysqli, boolean given in E:\xampp\htdocs\PhpProject1\index.php on line 7
Failure
This way I can't get the new DB created. Does anybody has any idea how to correct this?
Three steps to fix this:
CREATE DATABASE IF NOT EXISTS php1
.mysqli_select_db($link, 'php1')
to make that the default database for your connection.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With