allanth
allanth

Reputation: 441

How to connect to SQL server from php (Laravel)

On a Linux/Ubuntu box, I'm trying to connect to an external SQL Server database, but I only get errors. I know that the hostname, db name and credentials are correct, and I can't change them.

$odbc="odbc:Driver={SQL Server};Server=$server;Database=$database;";
$db = new PDO($odbc, $user, $password);

This just gives me could not find driver. I have tried every tutorial I could find, and installed tons of packages, and restarted nginx over and over again. I don't know what to do next.

Upvotes: 1

Views: 9257

Answers (1)

Travis Britz
Travis Britz

Reputation: 5552

You need to install drivers for php: https://learn.microsoft.com/en-us/sql/connect/php/download-drivers-php-sql-server?view=sql-server-2017

Then update config/database.php to use the sqlserv connection and driver:

'default' => env('DB_CONNECTION', 'sqlsrv'),

'connections' => [

    'sqlsrv' => [
       'driver'   => 'sqlsrv',
       'host'     => env('DB_HOST',     'localhost'),
       'database' => env('DB_DATABASE', 'default_database'),
       'username' => env('DB_USERNAME', 'default_username'),
       'password' => env('DB_PASSWORD', ''),
       'prefix' => '',
      ],

    //[...]
],

After you've done that, you can use php artisan tinker to confirm the driver is available:

>>> DB::availableDrivers()
=> [
     0 => "mysql",
     2 => "sqlite",
   ]

and test your connection:

>>> DB::connection()
=> Illuminate\Database\MySqlConnection {#161}

(Mine doesn't show sqlserv because I don't use that driver)

Upvotes: 1

Related Questions