@Div-Man

Почему не подключается к базе?

Почему пишет, то, что db не определен, если она есть?

<?php 
	error_reporting(E_ALL);
	
	class DB
	{
		private static $db;
		private $host = 'localhost';
		private $dbname = 'test';
		private $charset = 'utf8';
		private $username = 'root';
		private $password = '';
		
		static public function connect()
		{
			if (static::$db === Null) {
				static::$db = new \PDO("mysql:host=".$db->host.";dbname=".$db->dbname.";charset=".$db->charset,
										$db->username, $db->password);
			}
			return static::$db;
		}
	 
	}
	
	$db = DB::connect();

Текст ошибки
Notice: Undefined variable: db in C:\xampp\htdocs\dashboard\phphtml\43\dz\12.php on line 16

Notice: Trying to get property of non-object in C:\xampp\htdocs\dashboard\phphtml\43\dz\12.php on line 16

Notice: Undefined variable: db in C:\xampp\htdocs\dashboard\phphtml\43\dz\12.php on line 16

Notice: Trying to get property of non-object in C:\xampp\htdocs\dashboard\phphtml\43\dz\12.php on line 16

Notice: Undefined variable: db in C:\xampp\htdocs\dashboard\phphtml\43\dz\12.php on line 16

Notice: Trying to get property of non-object in C:\xampp\htdocs\dashboard\phphtml\43\dz\12.php on line 16

Notice: Undefined variable: db in C:\xampp\htdocs\dashboard\phphtml\43\dz\12.php on line 17

Notice: Trying to get property of non-object in C:\xampp\htdocs\dashboard\phphtml\43\dz\12.php on line 17

Notice: Undefined variable: db in C:\xampp\htdocs\dashboard\phphtml\43\dz\12.php on line 17

Notice: Trying to get property of non-object in C:\xampp\htdocs\dashboard\phphtml\43\dz\12.php on line 17

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY000] [2019] Unknown character set' in C:\xampp\htdocs\dashboard\phphtml\43\dz\12.php:17 Stack trace: #0 C:\xampp\htdocs\dashboard\phphtml\43\dz\12.php(17): PDO->__construct('mysql:host=;dbn...', NULL, NULL) #1 C:\xampp\htdocs\dashboard\phphtml\43\dz\12.php(24): DB::connect() #2 {main} thrown in C:\xampp\htdocs\dashboard\phphtml\43\dz\12.php on line 17
  • Вопрос задан
  • 1916 просмотров
Пригласить эксперта
Ответы на вопрос 3
lxfr
@lxfr
А какую ошибку выдает то? :)
Ответ написан
slo_nik
@slo_nik Куратор тега PHP
Замените $db->host на $this->host, остальные тоже поменяйте.
Ответ написан
class DB
  {
    private static $db;
    private $host = 'localhost';
    private $dbname = 'test';
    private $charset = 'utf8';
    private $username = 'root';
    private $password = '';
    
    static public function connect()
    {
      if (self::$db === Null) {
        self::$db = new self();
      }
      return self::$db;
    }
    private function __clone() {}
    private function __construct()
   {
      return new \PDO("mysql:host=".$this->host.";dbname=".$this->dbname.";charset=".$this->charset, $this->username, $this->password);
   }
  }
  
  $db = DB::connect();
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы