1.准备知识
在ubuntu实现php访问mssql,数据库版本SQL Server 2008R2。注意所安装驱动与php版本的对方关系。官方文档:微软官方方法:https://www.microsoft.com/en-us/sql-server/developer-get-started/php/ubuntu
php官方sqlsrv版本对应关系:https://pecl.php.net/package/pdo_sqlsrv/5.8.0
从以上可知及php7.2以下,只能安装sqlsrv-5.8.0。
参考https://serverok.in/install-php-drivers-for-microsoft-sql-server-on-ubuntu-php-7-2
以下操作是php7.2,但php7.4安装失败。若是php8.0环境,需要安装最新的sqlsrv即可。
2.apt安装php7.2环境
apt install php7.2-dev
3.Instal php modules with pcel
pecl install sqlsrv-5.8.0
此时报错:
#include <sql.h>
compilation terminated.
Makefile:194: recipe for target 'conn.lo' failed
make: *** [conn.lo] Error 1
ERROR: `make' failed
4.修复错误
apt-get install unixodbc-dev
5.安装sqlsrv
pecl install pdo_sqlsrv-5.8.0
报错,可按提示更新源:sudo pecl channel-update pecl.php.net
6.用root账号保存配置
printf "; priority=20\nextension=sqlsrv.so\n" > /etc/php/7.2/mods-available/sqlsrv.ini
printf "; priority=30\nextension=pdo_sqlsrv.so\n" > /etc/php/7.2/mods-available/pdo_sqlsrv.ini
7.phpenmod
phpenmod -v 7.2 sqlsrv pdo_sqlsrv
若是php8.0环境,注意换成8.0。重启php程序,此时在phpinfo()中,会显示出pdo_sqlsrv已启用及版本号。
但php脚本有错误,如下:
This extension requires the Microsoft ODBC Driver for SQL Server to communicate with SQL Server. Access the following URL to download the ODBC Driver for SQL Server for x64
8.用root账号修复如下
curl https://packages.microsoft.com/keys/microsoft.asc | apt-key add -
接着,其他操作系统版本可参考微软官方。
curl https://packages.microsoft.com/config/ubuntu/18.04/prod.list > /etc/apt/sources.list.d/mssql-release.list
9.更新系统
apt-get update
10.安装odbc
apt-get install -y msodbcsql17
若是php8版本,仍是msodbcsql17,至此php脚本可以访问mssql数据库,其他可选的安装有:
apt-get install -y mssql-tools
echo 'export PATH="$PATH:/opt/mssql-tools/bin"' >> ~/.bashrc
source ~/.bashrc
apt-get install -y unixodbc-dev
10.php脚本样例:
try{ $conn = new PDO("sqlsrv:server=120.77.23.*;database=HWMS","HMS","Gold2011Valley"); var_dump($conn); $sql = "select * from StoreIn"; $res = $conn->query($sql); var_dump($res->fetch()); } catch(Exception $e){ var_dump($e); }