How to query if database exists in php

藏色散人
Release: 2023-03-06 12:20:01
Original
4829 people have browsed it

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']:数据库密码
Copy after login
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']为数据库用户名
Copy after login
function isDBExist($config)
{
       try {
 
            $rs = Db::execute("use ".$db_config["database"]);
        }catch (Exception $e)
        {
            return false;//不存在
        }
        return true;
}
Copy after login

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!

Related labels:
php
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!