Hints to connect to MS SQL server via Linux PHP PDO or mssql_ functions

Hints to connect to MS SQL server via Linux PHP PDO or mssql_ functions

1. Make sure you reach the port 1433 on the machine the SQL Server is running. Use telnet in this purpose.

2. On window station SQL Server is running, open a cmd.exe terminal and enter netstat -na command. Check the 1433 port is open and listening.

3. If you can t see the port opened, check this article : http://blogs.msdn.com/b/walzenbach/archive/2010/04/14/how-to-enable-remote-connections-in-sql-server-2008.aspx

4. If SQL server is placed inside LAN, make the proper port fowarding rule on your router.

5. Make sure no firewall is blocking port 1433

6. Use tsql utility ( found in /usr/local/freetds/bin ) to test connection . Before doing so, fill in freetds.conf ( /usr/local/freetds/etc ) with SQL server parameters.

# A typical Microsoft server
[mymssql]
host = 187.215.96.225 ( put sql server IP )
port = 1433
tds version = 7.0

This might help http://www.freetds.org/userguide/confirminstall.htm

7. Check again your phpinfo page. You should see MSSQL section and pdo_dblib section

7. Now it s time to create connection in your php script

For those who still use mssql_* functions , here is a sample connection script

 

For PDO style

try {
$hostname = „mymssql”;
$port = 1433;
$dbname = „DBname”;
$username = „MSSQLusername”;
$pw = „MSSQLpassword”;
$dbh = new PDO („dblib:host=$hostname:$port;dbname=$dbname”,”$username”,”$pw”);
} catch (PDOException $e) {
echo „Failed to get DB handle: ” . $e->getMessage() . „\n”;
exit;
}

$stmt = $dbh->prepare(„select * from table”);
$stmt->execute();
while ($row = $stmt->fetch()) {
print_r($row);
}
unset($dbh); unset($stmt);
?>

Good Luck !

About the Author

Mircea Dragota este manager de proiecte si membru al echipei de dezvoltatori CCMS

Comentariu

Your email address will not be published.