我需要一些有关数据库连接的帮助。
我有我的config.php:
namespace App\Core;
class config
{
private $db;
private $host;
private $user;
private $password;
private $charset;
private $opt;
private $dsn;
public function __construct()
{
$this->db = 'example';
$this->host = '127.0.0.1';
$this->user = 'root';
$this->password = '';
$this->charset = 'utf8';
$this->dsn = "mysql:host=$this->host;DBName=$this->db;charset=$this->charset;";
$this->opt = array(
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
\PDO::ATTR_EMULATE_PREPARES => false
);
}
// getters
public function db()
{
return $this->db;
}
public function host()
{
return $this->host;
}
public function user()
{
return $this->user;
}
public function password()
{
return $this->password;
}
public function charset()
{
return $this->charset;
}
public function options()
{
return $this->opt;
}
public function dsn()
{
return $this->dsn;
}
}
我选择使用配置类。
然后,我也有一个DBHandler类。这是我建立PDO连接的地方,也可能是哪里出错了。
public function __construct()
{
$this->config = new config();
try {
$this->PDO = new \PDO($this->config->dsn(), $this->config->user(), $this->config->password(), $this->config->options());
} catch (\PDOException $e) {
throw new \PDOException($e->getMessage(), (int)$e->getCode());
}
}
public static function getInstance()
{
if (!isset(self::$instance)) {
self::$instance = new DBHandler();
}
return self::$instance;
}
public function connect()
{
return $this->PDO;
}
然后,我还有一个DBHelper,基本上是我的CRUD类,在这里我编写了所有查询,这是我在所有常规PHP文件(例如“ index.php”)中调用的文件。
每当我尝试运行查询时,我都会得到一个错误,所以我var_dumped $ db并得到了这个错误:
严重错误:未捕获的PDOException:SQLSTATE [3D000]:无效的目录名称:1046在D:\ App \ Core \ DBHelper.php:28中未选择数据库:堆栈跟踪:#0 D:\ App \ Core \ DBHelper.php (28):PDO-> prepare('SELECT * FROM u ...')#1 D:\ App \ Core \ DBHelper.php(55):App \ Core \ DBHelper-> userQuery('SELECT * FROM u。 ..')#2 D:\ App \ index.php(28):App \ Core \ DBHelper-> select('users','*','userName',NULL)#3 {main}抛出D:第28行的\ App \ Core \ DBHelper.php
谁能告诉我哪里出了问题?