0

I want to check if a database exists or not using PDO only(if available). Also, if it's not possible, please provide me a quick solution on how to check database existence using if else statement. Any help is appreciated. Thank You!

Here's what I have done so far:

try {
    $conn = new PDO("mysql:host=localhost", "root", "");
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    //Now since I have been connected, I want to check DB existence.
    if(DB exists)
    {
        //check table existence
    }
    else {
        //Create DB
    }
}
catch(PDOException $e)
{
    echo "Connection failed: " . $e->getMessage();
}
2
  • 1
    Does this answer your question? How to check if mysql database exists Commented Dec 5, 2019 at 4:57
  • No actually this is done with mysql_* which is deprecated in php 7. I want to use PDO only as PDO supports other tyeps of databases. Commented Dec 5, 2019 at 6:19

1 Answer 1

1
try {
    $conn = new PDO("mysql:host=localhost", "root", "");
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    //Now since I have been connected, I want to check DB existence.
    $databases = $conn->query('show databases')->fetchAll(PDO::FETCH_COLUMN);

    if(in_array(YOUR_DATABASE_NAME,$databases))
    {
        //check table existence
    }
    else {
        //Create DB
    }
}
catch(PDOException $e)
{
    echo "Connection failed: " . $e->getMessage();
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank You! I found this extremely helpful! :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.