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 for diafol

What about in phpinfo() ?

Its showing.
Capture-phpinfo.JPG

Member Avatar for diafol

Which DB type are you using?

MSSQL

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 diafol

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;
    }
}
?>
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.