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

How to query whether database exists in php

藏色散人
藏色散人Original
2020-11-17 09:52:234480browse

How to query whether the database exists: first create a new instance of MySQL or MySQL; then execute the statement "SELECT COUNT(*) AS `exists` FROM..."; finally check the value of the key exists, and Just check whether the database exists.

How to query whether database exists in php

Recommended: "PHP Video Tutorial"

Create a new instance of MySQL or MySQL (without specifying a default database) , and execute the following query (similar to Marc B's comment):

SELECT COUNT(*) AS `exists` FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMATA.SCHEMA_NAME='my_database_name'

Then you can check the value of key exists to see if the database exists.

The following is a sample code:

// statement to execute
$sql = 'SELECT COUNT(*) AS `exists` FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMATA.SCHEMA_NAME="my_database_name"';
// execute the statement
$query = $mysqli->query($sql);
if ($query === false) {
    throw new Exception($mysqli->error, $mysqli->errno);
}
// extract the value
$row = $query->fetch_object();
$dbExists = (bool) $row->exists;

The above is the detailed content of How to query whether 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