How to connect to MSSQL Server with PHP from Ubuntu 18.04?



PHP Snippet 1:

sudo bash -c "echo extension=sqlsrv.so > /etc/php/7.2/mods-available/sqlsrv.ini"
sudo ln -s /etc/php/7.2/mods-available/sqlsrv.ini /etc/php/7.2/apache2/conf.d/sqlsrv.ini
sudo ln -s /etc/php/7.2/mods-available/sqlsrv.ini /etc/php/7.2/cli/conf.d/sqlsrv.ini
sudo bash -c "echo extension=pdo_sqlsrv.so > /etc/php/7.2/mods-available/pdo_sqlsrv.ini"
sudo ln -s /etc/php/7.2/mods-available/pdo_sqlsrv.ini /etc/php/7.2/apache2/conf.d/pdo_sqlsrv.ini
sudo ln -s /etc/php/7.2/mods-available/pdo_sqlsrv.ini /etc/php/7.2/cli/conf.d/pdo_sqlsrv.ini


sudo systemctl restart apache2

PHP Snippet 2:

//format: serverName\instanceName, portNumber (default is 1433)
$serverName = "localhost";

$connectionInfo = array("Database" => "dbName", "UID" => "myUserName", "PWD" => "myPassword");
$conn = sqlsrv_connect($serverName, $connectionInfo);

if ($conn) {
    echo "Got a connection!<br />";
} else {
    echo "Connection could not be established.<br />";
    die(print_r(sqlsrv_errors(), true));
}