Home  >  Article  >  Backend Development  >  How to query if database exists in php

How to query if database exists in php

藏色散人
藏色散人Original
2020-10-06 09:39:014736browse

How to query whether the database exists in php: 1. Use PDO to determine whether the database exists; 2. Use SQL statements to determine whether the database exists.

How to query if database exists in php

Recommended: "PHP Video Tutorial"

PHP determines whether the database exists

1. Two methods to determine whether the database exists:

1. Use PDO to determine whether the database exists

2. Use SQL statements to determine

2. Method 1 executes the code as follows:

//$config['dsn']的表示如下
$config["dsn"] => string(65) "mysql:host=127.0.0.1;port=3306;charset=utf8"
//$config['username']为数据库用户名, $config['password']:数据库密码
function isDBExist($config)
{
    $config['dsn'] = $this->parseDsn($config);//转换组为DSN字符串
 
    $conn = new PDO($config['dsn'], $config['username'], $config['password']);
    // 设置 PDO 错误模式为异常
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $sql = "show databases;";
    // 使用 exec() ,因为没有结果返回
    $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. 方法二执行代码如下:
//$config['username']为数据库用户名
function isDBExist($config)
{
       try {
 
            $rs = Db::execute("use ".$db_config["database"]);
        }catch (Exception $e)
        {
            return false;//不存在
        }
        return true;
}

The above is the detailed content of How to query if database exists in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn