php查詢數(shù)據(jù)庫是否存在的方法:1、用PDO判斷數(shù)據(jù)庫是否存在;2、使用SQL語句判斷數(shù)據(jù)庫是否存在。
推薦:《PHP視頻教程》
PHP判斷數(shù)據(jù)庫是否存在
1. 判斷數(shù)據(jù)庫是否存在的兩種方法:
一、用PDO判斷數(shù)據(jù)庫是否存在
二、用SQL語句判斷
2. 方法一執(zhí)行代碼,如下:
//$config['dsn']的表示如下 $config["dsn"] => string(65) "mysql:host=127.0.0.1;port=3306;charset=utf8" //$config['username']為數(shù)據(jù)庫用戶名, $config['password']:數(shù)據(jù)庫密碼
function isDBExist($config) { $config['dsn'] = $this->parseDsn($config);//轉(zhuǎn)換組為DSN字符串 $conn = new PDO($config['dsn'], $config['username'], $config['password']); // 設(shè)置 PDO 錯誤模式為異常 $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $sql = "show databases;"; // 使用 exec() ,因為沒有結(jié)果返回 $res = $conn->query($sql); $res = $res->fetchAll(PDO::FETCH_ASSOC); $database_list = []; foreach($res as $k => $v) { $database_list[] = $v['Database']; } if (in_array($config['database'],$database_list)) { return true; // 存在 } else { return false; } } 2. 方法二執(zhí)行代碼如下: //$config['username']為數(shù)據(jù)庫用戶名
function isDBExist($config) { try { $rs = Db::execute("use ".$db_config["database"]); }catch (Exception $e) { return false;//不存在 } return true; }