Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create DB if not exists using mysqli + php

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?

like image 587
Amrit Avatar asked Mar 27 '15 18:03

Amrit


1 Answers

Three steps to fix this:

  1. Don’t specify the database name when connecting.
  2. Your SQL statement should be CREATE DATABASE IF NOT EXISTS php1.
  3. Call mysqli_select_db($link, 'php1') to make that the default database for your connection.
like image 113
Nate Avatar answered Sep 23 '22 02:09

Nate