Tuesday, July 21, 2015

Ubuntu Lampp Xampp MSSQL PHP5

I had some issues with using MSSQL on my ubuntu server past migration, as my code was using sqlsrv_connect being on Windows Xampp installation.

After migration to Linux host I had to resolve errors like this:

Fatal error: Call to undefined function sqlsrv_connect()
Unable to connect to server: 


Here is how to connect to MS SQL server using Ubuntu Xampp.



Assuming your installation is located here
/opt/lampp/your_files_live_here

You will need to install these:
sudo apt-get install freetds-common freetds-bin unixodbc php5-sybase
sudo apt-get install php5-cli

You will see there are at least two freetds.conf files. You need the one located in your lampp folder





Edit you php.ini and in appropriate place put:


sudo nano /opt/lampp/etc/php.ini
extension = mssql.so

Also make sure that mssql_secureconnection =Off

Save php.ini


Go ahead and edit


  • sudo nano /opt/lampp/etc/freetds.conf
Put this in:

[SQLServerReference]
        host = server.domain.com  (or IP address)
        port = 1433
        tds version = 8.0


Once done

sudo /opt/lampp/lampp restart

And in your PHP code reference it as follows:

$SQL_server='SQLServerReference';
$SQL_username='SA';
$SQL_password='password';
$SQL_database='your_database';
You can now use it in your code:


//connect to  MS SQL database
$conn = mssql_connect( $SQL_server,$SQL_username,$SQL_password)
   or die("Couldn't connect to SQL Server on $SITS_server"); 
   //select a database to work with
$selected = mssql_select_db($SQL_database, $conn)
  or die("Couldn't open database $SQL_database"); 
//get  data from SQL database
$result = mssql_query("select whatever from dbo.table);
while( $row = mssql_fetch_array($result) ) 
 {
$string = $row['whatever'];
}
mssql_close( $conn);


If you need ODBC connection


sudo nano /etc/odbc.ini 

[SQLServerRef]
Description = MS SQL Server
Driver = /usr/lib/x86_64-linux-gnu/odbc/libtdsodbc.so
Server = sqlserver.domain.com
ID = username
PWD = password
ReadOnly = No
Port = 1433

Look at the driver path - other tutorials will have it different. If unsure, use 
locate libtdsodbc.so
To see where is your file

Also edit this and note the paths again
sudo nano /etc/odbcinst.ini 
[FreeTDS]
Description = FreeTDS driver
Driver = /usr/lib/x86_64-linux-gnu/odbc/libtdsodbc.so
Setup=/usr/lib/x86_64-linux-gnu/odbc/libtdsS.so
FileUsage = 1
UsageCount = 1


1 comment:

  1. buen aporte por fin lo logre gracias.
    TambiƩn tome como referencia el siguiente enlace.
    https://es.stackoverflow.com/questions/182365/como-instalar-en-xampp-con-php-7-2-el-pdo-sqlsrv-driver-de-sql-server-2017-en-li

    NOTA:Mi experiencia fue en ubuntu 19.10 y Microsoft SQL Server 2019

    Saludos,
    Jose Lujan

    ReplyDelete