Thursday, July 28, 2011

PHP and MS SQL Server connection in IIS 7


<?php
$connectionInfo = array("UID" => "sa", "PWD" => "asdf123*", "Database"=>"testdb");
$serverName = ".\SQLEXPRESS";
$conn = sqlsrv_connect( $serverName, $connectionInfo);

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

//Lets do some sample sql select.

// Send a select query to MSSQL
$stmt = sqlsrv_query($conn,'SELECT * FROM users');
if( $stmt === false)
{
     echo "Error in query preparation/execution.\n";
     die( print_r( sqlsrv_errors(), true));
}
// Check if there were any records
if (sqlsrv_has_rows($stmt)==false) {
    echo 'No records found';
} else {
?>
<table width="100%" border="2px">
<?php while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) { ?>
<tr>
    <td><?php echo $row['name']; ?></td>
    <td><?php echo $row['designation']; ?></td>
</tr>
<?php } ?>
</table>
<br /> <?php
}
// Free the query result
sqlsrv_free_stmt($stmt);

/* Close the connection. */
sqlsrv_close($conn);

phpinfo();
?>

No comments:

Post a Comment