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();
}
Anirban
  • 19
  • 1
  • 8
  • 1
    Does this answer your question? [How to check if mysql database exists](https://stackoverflow.com/questions/838978/how-to-check-if-mysql-database-exists) – FullStackOfPancakes Dec 05 '19 at 04: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. – Anirban Dec 05 '19 at 06:19

1 Answers1

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();
}
liquid207
  • 176
  • 5