6 July 2019

Connect to mssql server in CodeIgniter 3. This will probably apply on any php version, just I had v 7.3 at this point. The setup is really easy, I even used mssql on my linux machine locally.

I am using "Microsoft ODBC Driver 17 for SQL Server" ("msodbcsql" package) as the driver. You can download the package from your Linux repository.
Enable pdo by uncommenting this line in php.ini.
Source code viewer
  1. extension=pdo_odbc
Programming Language: INI
The most important thing is to get the dsn right. You can use other drivers, check "/etc/odbcinst.ini" file for installed drivers on your system. You can set and use predefined connection configurations at "/etc/odbc.ini".
Source code viewer
  1. $db['default'] = array(
  2. 'dsn' => 'odbc:Driver={ODBC Driver 17 for SQL Server};Server=localhost;Database=' . $database,
  3. 'hostname' => '',
  4. 'username' => 'sa',
  5. 'password' => $password,
  6. 'database' => '',
  7. 'dbdriver' => 'pdo',
  8. 'dbprefix' => '',
  9. ...
  10. );
Programming Language: PHP
Test your connection on a select query in a controller.
Source code viewer
  1. $this->load->database();
  2.  
  3. $query = $this->db->query("SELECT * FROM $schema.$table");
  4. $row = $query->row_array();
  5. print_r($row);
Programming Language: PHP