Logan Kling
Logan Kling

Reputation: 589

Why is my PHP not connecting to my MySQL database?

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!

Upvotes: 0

Views: 106

Answers (3)

Jesse Hockenbury
Jesse Hockenbury

Reputation: 114

mysqli_select_db($connection, $db);

Upvotes: 2

jordan
jordan

Reputation: 1017

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.

Upvotes: 0

Fosco
Fosco

Reputation: 38526

Try:

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

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

Upvotes: 2

Related Questions