Saturday, January 31, 2009

use php to connect to MS SQL server


<?php
$myServer = "localhost";
$myUser = "";
$myPass = "";
$myDB = "";

//create an instance of the ADO connection object
$conn = new COM ("ADODB.Connection")
or die("Cannot start ADO");

//define connection string, specify database driver
$connStr = "PROVIDER=SQLOLEDB;SERVER=".$myServer.";UID=".$myUser.";PWD=".$myPass.";DATABASE=".$myDB;
$conn->open($connStr); //Open the connection to the database

//declare the SQL statement that will query the database
$query = "SELECT * FROM test_member";

//execute the SQL statement and return records
$rs = $conn->execute($query);

$num_columns = $rs->Fields->Count();
echo $num_columns . "
";

for ($i=0; $i < $num_columns; $i++) {
$fld[$i] = $rs->Fields($i);
}

echo "";

while (!$rs->EOF) //carry on looping through while there are records
{
echo "";
for ($i=0; $i < $num_columns; $i++) {
echo "";
}
echo "";
$rs->MoveNext(); //move on to the next record
}


echo "
" . $fld[$i]->value . "
";

//close the connection and recordset objects freeing up resources
$rs->Close();
$conn->Close();

$rs = null;
$conn = null;
?>

No comments: