Jump to Navigation

006 - To connect MS SQL Server

This is a sample program for connecting to MS SQL Server.

<html>
<head>
<title>driver test</title>
</head>
<body>
<h1><small>php microsoft driver test</small></h1>
<hr>
<?php
$myServer = "192.168.210.114";
$myUser = "username";
$myPass = "password";
$myDB = "dbname";
// connection to the database
$dbhandle = mssql_connect($myServer, $myUser, $myPass)
or die("Couldn't connect to SQL Server on $myServer");
if(!$dbhandle)
{
die('Something went wrong while connecting to MSSQL');
}
// select a database to work with
$selected = mssql_select_db($myDB, $dbhandle)
or die("Couldn't open database $myDB");
echo "You are connected to the " . $myDB . " database on the " . $myServer . ".<br />";
// Select data from SQL Server
$p_id = '01441';
$stmt = mssql_query('SELECT PROD_ID, PROD_DESC FROM PROD_MASTER WHERE PROD_ID = ' . $p_id);
if(!$stmt) {
die('Query failed.');
}
print '<table border="1">';
while($row = mssql_fetch_array($stmt, MSSQL_ASSOC)) {
print '<tr>';
foreach($row as $item) {
print '<td>' . ($item?htmlentities($item):'&nbsp;') . '</td>';
}
print '</tr>';
}
print '</table>';
print '<p>Totla records in database: ' . mssql_num_rows($stmt) . '</p>';
// Free the query result
mssql_free_result($stmt);
// close the connection
mssql_close($dbhandle);
?>
<hr>
</body>
</html>


Main menu 2

Story | by Dr. Radut