Мне нужна помощь с подключением к БД.
У меня есть мой 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 и получаю из него эту ошибку:
Неустранимая ошибка: Uncaught 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 * FROMu ... ') # 2 D: \ App \ index.php (28): добавлено приложение \ Core \ DBHelper-> select (' users ',' * ',' userName ', NULL) # 3 {main}D: \ App \ Core \ DBHelper.php в строке 28
Может кто-нибудь сказать мне, где это идет не так?