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.

Re: connection function using odbc with PDO OOP 80 80

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

Re: connection function using odbc with PDO OOP 80 80

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

Re: connection function using odbc with PDO OOP 80 80
Member Avatar

What about in phpinfo() ?

Re: connection function using odbc with PDO OOP 80 80

Its showing.
Capture-phpinfo.JPG

Re: connection function using odbc with PDO OOP 80 80
Member Avatar

Which DB type are you using?

Re: connection function using odbc with PDO OOP 80 80

MSSQL

Re: connection function using odbc with PDO OOP 80 80

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

Re: connection function using odbc with PDO OOP 80 80

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

Re: connection function using odbc with PDO OOP 80 80

Thanks, Now its working.

Re: connection function using odbc with PDO OOP 80 80
Member Avatar

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

Re: connection function using odbc with PDO OOP 80 80

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 1.19 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.