'how to see if database exists with PDO [duplicate]

So I recently decided to switch to PDO due to the mysqli prepared statement complexity and irregularities. This was my mysqli function to test for a database:

public static function is_database($database) {
    self::connect();
    if( mysqli_select_db(self::$conn,$database) ) {
        self::$dbname = $database;
        return true;
    } else {
        return false;
    }
    self::disconnect();
}

The only thing I've read so far about PDO and a database of anything was this:

$pdo->exec("use database");

Which is not what I want, unless using this with a try catch would work. Something of this sort

public static function is_database($database){
   self::connect();
   try {
      self::$conn->exec('use '.$database);
      return true;
   } catch(PDOException $e){
     print($e->getMessage();
     return false;
     die();
   }
}

Need a little assistance for the 1 hour new PDO user. Thanks for any advice.



Solution 1:[1]

In accordance with the query found at How to check if mysql database exists

$stmt = $pdo->query("SELECT COUNT(*) FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = 'DBName'");
return (bool) $stmt->fetchColumn();

We check the count which will return 1 or 0 and type cast it as an boolean (true/false).

Of course this requires an existing connection through PDO. This wouldn't work for you to check the database before the first connection.

Solution 2:[2]

A very simple answer execute your code in "try-catch" exception; and if you want to throw an error then echo your error and if you don't then just live empty your catch block; how useful try catchs are

  1. if DB does not exist it will create
  2. error of your choice or no error

the example is given below.

        try {
            $conn->exec($sql);
        } catch (PDOException $th) {
            echo "<br> sql error";
        }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Your Common Sense
Solution 2