Connection error: SQLSTATE[HY000] [2002] No such file or directory

Hello,

I can’t connect to my database. This my code to connect:

    class Database
{
        private $server = "localhost";
	private $login = "id9551308_user";
	private $password = "*****";
	private $database = "id9551308_konzole";
    public $conn;

  public function dbConnection()
   {
      $this->conn = null;
          try
      {
      $this->conn = new PDO("mysql:host=" . $this->dbserver . ";dbname=" . $this->dbname.";charset=utf8", $this->dbuser, $this->dbpass);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  }
catch(PDOException $exception)
{
  echo "Connection error: " . $exception->getMessage();
  }
  return $this->conn;
 }
}
$DB = new Database();
$conn = $DB->dbConnection();

I tried it with XAMPP and everything was working so whats wrong? Can somebody help me?

Does the code emit any error?

PDO example?

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$database = "database";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$database", $username, $password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Connected successfully"; 
    } catch(PDOException $e) {    
    echo "Connection failed: " . $e->getMessage();
    }
?>
1 Like

It’s working. Thank you very much!