步骤 3:使用 PHP 连接到 SQL 的概念证明
步骤 1:连接
此 OpenConnection 函数在后跟的所有函数的顶部附近位置调用。
function OpenConnection()
{
$serverName = "tcp:myserver.database.windows.net,1433";
$connectionOptions = array("Database"=>"AdventureWorks",
"Uid"=>"MyUser", "PWD"=>"MyPassword");
$conn = sqlsrv_connect($serverName, $connectionOptions);
if($conn == false)
die(FormatErrors(sqlsrv_errors()));
return $conn;
}
步骤 2:执行查询
sqlsrv_query() 函数可用于针对 SQL 数据库从查询中检索结果集。 此函数实质上接受任意查询和连接对象,并返回可使用 sqlsrv_fetch_array() 循环访问的结果集。
function ReadData()
{
try
{
$conn = OpenConnection();
$tsql = "SELECT [CompanyName] FROM SalesLT.Customer";
$getProducts = sqlsrv_query($conn, $tsql);
if ($getProducts == FALSE)
die(FormatErrors(sqlsrv_errors()));
$productCount = 0;
while($row = sqlsrv_fetch_array($getProducts, SQLSRV_FETCH_ASSOC))
{
echo($row['CompanyName']);
echo("<br/>");
$productCount++;
}
sqlsrv_free_stmt($getProducts);
sqlsrv_close($conn);
}
catch(Exception $e)
{
echo("Error!");
}
}
步骤 3:插入行
此示例展示了如何安全地执行 INSERT 语句和传递参数。 参数值保护应用程序不受 SQL 注入影响。
function InsertData()
{
try
{
$conn = OpenConnection();
$tsql = "INSERT SalesLT.Product (Name, ProductNumber, StandardCost, ListPrice, SellStartDate) OUTPUT"
. " INSERTED.ProductID VALUES ('SQL Server 1', 'SQL Server 2', 0, 0, getdate())";
//Insert query
$insertReview = sqlsrv_query($conn, $tsql);
if($insertReview == FALSE)
die(FormatErrors( sqlsrv_errors()));
echo "Product Key inserted is :";
while($row = sqlsrv_fetch_array($insertReview, SQLSRV_FETCH_ASSOC))
{
echo($row['ProductID']);
}
sqlsrv_free_stmt($insertReview);
sqlsrv_close($conn);
}
catch(Exception $e)
{
echo("Error!");
}
}
步骤 4:回滚事务
此代码示例演示了可以在其中执行以下操作的事务的用法:
开始一个事务
插入一行数据,更新另一行数据
-如果插入和更新操作都成功,则提交事务;如果其中任一操作失败,则回滚事务
function Transactions()
{
try
{
$conn = OpenConnection();
if (sqlsrv_begin_transaction($conn) == FALSE)
die(FormatErrors(sqlsrv_errors()));
$tsql1 = "INSERT INTO SalesLT.SalesOrderDetail (SalesOrderID,OrderQty,ProductID,UnitPrice)
VALUES (71774, 22, 709, 33)";
$stmt1 = sqlsrv_query($conn, $tsql1);
/* Set up and execute the second query. */
$tsql2 = "UPDATE SalesLT.SalesOrderDetail SET OrderQty = (OrderQty + 1) WHERE ProductID = 709";
$stmt2 = sqlsrv_query( $conn, $tsql2);
/* If both queries were successful, commit the transaction. */
/* Otherwise, rollback the transaction. */
if($stmt1 && $stmt2)
{
sqlsrv_commit($conn);
echo("Transaction was committed");
}
else
{
sqlsrv_rollback($conn);
echo "Transaction was rolled back.\n";
}
/* Free statement and connection resources. */
sqlsrv_free_stmt( $stmt1);
sqlsrv_free_stmt( $stmt2);
}
catch(Exception $e)
{
echo("Error!");
}
}