问题描述
我正在使用 PDO 连接到 mySql 数据库.尽管我可以连接到已创建的数据库(默认情况下已创建),但我无法连接到我创建的任何数据库.我正在使用 wamp 服务器.
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()}");
}
?>
如果我用之前在 wamp 服务器中创建的数据库 mysql 替换 mydata,那么代码就可以完美运行.唯一的问题是我创建的数据库.我曾尝试为 mydata 赋予与 mysql 数据库相同的权限,但它不起作用.
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.
推荐答案
您的代码和 phpmyadmin 只是连接到不同的数据库服务器.例如,如果您的 PC 上安装了多个数据库服务器,则可能会发生这种情况.
Your code and your phpmyadmin are simply connecting to different database servers. It could happen, for example, if you have multiple database servers on your PC installed.
要获得证明,请在 phpmyadmin 中运行以下查询:
To get a proof, run the following query in phpmyadmin:
show databases;
然后在 PDO 中运行相同的查询:
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=$host", $user, $pass, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
$databases = $pdo->query('show databases')->fetchAll(PDO::FETCH_COLUMN);
var_dump($databases);
或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);
并比较输出.它会告诉您是否存在拼写错误,或者 phpmyadmin 和 PHP 确实连接到了不同的数据库服务器.
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.
然后您可以检查 PHPmyAdmin 中的配置文件以确保它连接到正确的服务器
Then you can check the configuration file in PHPmyAdmin to make sure it connects to the proper server
这篇关于Mysql - 无法连接未知数据库 'databasename' 错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!