0

I'm trying to connect to a database. If my php fails to connect to that database then it's programmed to create that database. I'm at a little bit of a dilemma, though; because I'm receiving this error: "Error creating database: Can't create database 'my_db'; database exists" So the database is there, but it appears that my php is unable to connect to it.

Here's my code:

<?php
    $db = "my_db";
    //establish a connection with the server
    $connection = mysqli_connect('localhost', 'root', '205360hello');
    if(!$connection){
        exit("<p>Could not establish a connection :" . mysqli_connect_error() . "</p>");
    }
    //connect to the database
    $dbSelect = mysqli_select_db($db);
    if(!$dbSelect){
        // Create database
        $sql="CREATE DATABASE " . $db;
        if (mysqli_query($connection, $sql)) {
        } else {
          echo "<p>Error creating database: " . mysqli_error($connection) . "</p>";
        }
    }
?>

Any help would be greatly appreciated!

1
  • 1
    Is there any reason you don't just want to do CREATE DATABASE IF NOT EXISTS my_db; and let the SQL Server handle the processing of this request? Commented May 6, 2014 at 0:19

3 Answers 3

2

Try:

$dbSelect = mysqli_select_db($connection, $db);

per: http://php.undmedlibrary.org/manual/en/function.mysqli-select-db.php

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

Comments

2

mysqli_select_db($connection, $db);

Comments

0

It looks like your PHP application is connecting, but it is giving a specific error message of "database exists", probably because you've already executed this code before.

Are you really trying to create a database with that same name, "my_db"? Or are you trying to do something else? If you are trying to create a database with that name, should you first check if it already exists? If so, dependi.g on your needs, you can delete it and create it again, or continue without creating it and reuse the one that was there.

Comments

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.