当前位置: 动力学知识库 > 问答 > 编程问答 >

php - how to see if database exists with PDO

问题描述:

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.

网友答案:

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.


For the initial connection, you could use a try, catch block assuming PDO's error mode is set to exceptions.

try { 
   $pdo = new PDO(...);
}
catch (PDOException $e) {
   die('Error: '.$e->getMessage().' Code: '.$e->getCode());
}

You'll have to dig further for a specific error message or code that coincides with a database not existing as this could mean a bad username/password or a non-existing MySQL server as well.

分享给朋友:
您可能感兴趣的文章:
随机阅读: