配置PHP操作MSSQL驱动
-
在指定目录安装PHP链接MSSQL驱动SQLSRV58.exe
新建一个文件夹,将驱动安装在该目录下,方便后边找。
也可以去微软官网找最新版驱动
-
复制对应版本的DLL至PHP,ext目录下
在步骤1安装驱动的目录下,选择对应版本的dll。
在PHP安装目录下找ext文件夹,并将对应版本的dll复制到改文件夹下:
以phpstudy的php为例:
…/phpstudy_pro/Extensions/php/php7.3.4nts/ext/
讲下列两个DLL 复制到上述目录下
php_sqlsrv_73_nts_x64.dll php_pdo_sqlsrv_73_nts_x64.dll
-
修改PHP配置文件php.ini
…/phpstudy_pro/Extensions/php/php7.3.4nts/
在该目录下找到php.ini文件
并添加如下代码:
extension=php_sqlsrv_73_nts_x64.dll extension=php_pdo_sqlsrv_73_nts_x64.dll
PHP操作MSSQL
-
链接数据库
function OpenConnection() { try { $serverName = "localhost"; //使用默认端口 //$serverName = "localhost,3306"; //使用指定端口 $connectionOptions = array("Database"=>"AdventureWorks", "Uid"=>"MyUser", "PWD"=>"MyPassword"); $conn = sqlsrv_connect($serverName, $connectionOptions); if($conn == false) die(FormatErrors(sqlsrv_errors())); } catch(Exception $e) { echo("Error!"); } }
-
执行sql(读取操作)
function ReadData() { try { $conn = OpenConnection(); $tsql = "SELECT [CompanyName] FROM SalesLT.Customer"; $getProducts = sqlsrv_query($conn, $tsql); //执行sql 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!"); } }
-
插入操作
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!"); } }
-
更多信息请查看微软官网