Connecting PHP to Microsoft SQL Server

Most developers don’t know this is possible, some arguably think it doesn’t make sense and others don’t even care whether it can be done or not because as far as they are concerned, PHP was always meant for MySQL. Well I’m not really going to go to the nitty gritty of the whole thing, we’ll save that for later, just going to show how its done.

Here’s a demo code. Replace the necessary variables.

<?php
/*
** Connect to  database:
*/
 
// Connect to the database (host, username, password)
$con = mssql_connect('servername','admin','password') 
 or die('Could not connect to the server!');
 
// Select a database:
mssql_select_db('stack') 
 or die('Could not select a database.');
 
// Example query: (TOP 10 equal LIMIT 0,10 in MySQL)
$SQL = "SELECT TOP 10 * FROM TableName ORDER BY ID ASC";
 
// Execute query:
$result = mssql_query($SQL) 
 or die('A error occured: ' . mysql_error());
 
// Get result count:
$Count = mssql_num_rows($result);
print "Showing $count rows:<hr/>\n\n";
 
// Fetch rows:
while ($Row = mssql_fetch_assoc($result)) {
 
 print $Row['Fieldname'] . "\n";
 
}
 
mssql_close($con);
?>

Note: Make sure php_mssql extension is turned on. This example was created on PHP version 5.3.1 so you might need to upgrade if it doesn’t work.

A Web designer and developer. Speaks PHP, Java, Javascript, HTML

Leave a Reply

Your email address will not be published. Required fields are marked *