Mysql - Couldn't connect unknown database 'databasename' error

你说的曾经没有我的故事 提交于 2020-04-26 06:09:24

问题


I am using PDO to connect to mySql database. I am not able to connect to any database that I create although I can connect to already created databases( already created by default). I am using wamp server.

<?php
try{
$dbh=new PDO("mysql:host=localhost;dbname=mydata","root","");
}catch(Exception $e){
    die("ERROR: Couldn't connect. {$e->getMessage()}");
}
?>

If i substitute mydata with mysql which is previously created database in wamp server, then the code works perfectly. The only problem is with the databases that I create. I have tried giving mydata the same privileges as mysql database but it doesn't work.


回答1:


you have multiple database servers on your PC running and your code and your phpmyadmin connect to different databases

To get a proof, run the following query in phpmyadmin:

show databases;

And then run the same query in PDO:

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

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

and compare the output. It will show you that either there is a spelling error or indeed phpmyadmin and PHP are connected to different database servers.




回答2:


try this way

change host=localhost; to host=127.0.0.1;



来源:https://stackoverflow.com/questions/60665821/mysql-couldnt-connect-unknown-database-databasename-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!