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.

Recommended Answers

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

Jump to Post

What about in phpinfo() ?

Jump to Post

Which DB type are you using?

Jump to Post

All 12 Replies

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() ?

Its showing.
Capture-phpinfo.JPG

Member Avatar

Which DB type are you using?

MSSQL

Yes, the PHP PDO ODBC driver is enabled, but is there an actual MSSQL ODBC driver installed on your machine?

How to: Set Up an ODBC Data Source

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

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