Home >Database >Mysql Tutorial >Why Does My PHP Code Show an 'Unknown Database Error' Even Though the Database Exists in phpMyAdmin?

Why Does My PHP Code Show an 'Unknown Database Error' Even Though the Database Exists in phpMyAdmin?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-07 19:27:16667browse

Why Does My PHP Code Show an

Unknown Database Error in PHP Despite Valid Database Existence in PHPMyAdmin

When attempting to connect to newly created MySQL databases using PDO in PHP, users may encounter an "unknown database error" despite the database being present in PHPMyAdmin. This issue is often attributed to one of two potential causes:

1. Spelling Errors

Ensure that the database name provided in the PHP code matches the exact name of the database created. Double-checking the spelling and casing is crucial.

2. Different Database Connections

It is possible that PHPMyAdmin and PHP are inadvertently connecting to different MySQL servers. To confirm this discrepancy, execute the following query in PHPMyAdmin:

show databases;

Subsequently, execute the same query in PHP using either PDO:

$host = 'your db host';
$user = 'your db username';
$pass = 'your db password';

$pdo = new PDO("mysql:host=$host", $user, $pass, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
$databases = $pdo->query('show databases')->fetchAll(PDO::FETCH_COLUMN);
var_dump($databases);

Or mysqli:

$host = 'your db host';
$user = 'your db username';
$pass = 'your db password';

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = mysqli_connect($host, $user, $pass);
$databases = $mysqli->query('show databases')->fetch_all();
var_dump($databases);

Comparing the output will reveal any discrepancies in database names or server connections. If PHP is connecting to a separate server, consult the PHPMyAdmin configuration file to verify that it is configured for the appropriate server.

The above is the detailed content of Why Does My PHP Code Show an 'Unknown Database Error' Even Though the Database Exists in phpMyAdmin?. 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