Hi

I am trying to connection my database ODBC using function.

I am getting an error Connection error: could not find driver

mycode is

<?php
class Database{

    // specify your own database credentials
    private $host = "servername";
    private $db_name = "databsename.schemaname";
    private $username = "username";
    private $password = "password";
    public $conn;

    // get the database connection
    public function getConnection(){

        $this->conn = null;

        try{
            $this->conn = new PDO("odbc:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
        }catch(PDOException $exception){
            echo "Connection error: " . $exception->getMessage();
        }

        return $this->conn;
    }
}
?>

Please help me to fix the issue.

Did you check if you have an ODBC driver for the database you are trying to connect to?

Yes. if i check php.ini file. its shows odbc

Member Avatar

What about in phpinfo() ?

Member Avatar

Which DB type are you using?

if i connect this by odbc_connect its working. but when i use PDO i am getting that error

Thanks, Now its working.

Member Avatar

For the benefit of others out there, could you please show the solution?

Here is the working code

<?php
class Database{

    // specify your own database credentials
    private $host = "odbc:Driver={SQL Server};server=servername;DATABASE=databasename";
    private $username = "username";
    private $password = "password";
    public $conn;

    // get the database connection
    public function getConnection(){

        $this->conn = null;

        try{
            $this->conn = new PDO($this->host, $this->username, $this->password);
        }catch(PDOException $exception){
            echo "Connection error: " . $exception->getMessage();
        }

        return $this->conn;
    }
}
?>