Troubleshooting Unknown Database Errors in PHP Despite Existence in PHPMyAdmin
PHP database connectivity issues can arise despite databases appearing in PHPMyAdmin. One possible cause is a spelling error in the database name provided in the PHP code. Reconfirming the spellings of both the PHP code and PHPMyAdmin is crucial.
Another potential issue is when the PHP code and PHPMyAdmin connect to separate database instances. This situation can occur in environments with multiple database servers installed. To verify this, execute the following query in PHPMyAdmin:
show databases;
Subsequently, execute the same query in PHP using either PDO or MySQLi:
PDO:
<code class="php">$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);</code>
MySQLi:
<code class="php">$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);</code>
Compare the outputs of both queries. If they differ, it indicates either a spelling error or separate database connections. Subsequently, review PHPMyAdmin's configuration file to ensure it connects to the appropriate server.
The above is the detailed content of Why Can\'t I Connect to a Database in PHP When It Exists in PHPMyAdmin?. For more information, please follow other related articles on the PHP Chinese website!