CentOS 7.6下宝塔面板 PHP7.2安装sqlsrv扩展


PHP需要的相关环境 (慎用 yum update)

yum update

yum install php php-pdo php-xml php-pear php-devel re2c gcc-c++ gcc

1、加微软源

curl https://packages.microsoft.com/config/rhel/7/prod.repo > /etc/yum.repos.d/mssqlrelease.repo

如果发现这个链接失效了,可以这个链接找下https://packages.microsoft.com/config/rhel/7/

卸载原有版本

yum remove unixODBC

2、安装驱动

yum install msodbcsql17 mssql-tools unixODBC-devel

3、下载pdo_sqlsrv扩展包 http://pecl.php.net/package/pdo_sqlsrv

wget http://pecl.php.net/get/pdo_sqlsrv-5.8.1.tgz

4、解压文件

tar -zxvf pdo_sqlsrv-5.8.1.tgz

5、进入解压目录

cd pdo_sqlsrv-5.8.1

6、宝塔路径下,使用对应php版本的phpize 进行编译和安装。我这里是php7.2,如果是php5.6就换成56

/www/server/php/72/bin/phpize

./configure --with-php-config=/www/server/php/72/bin/php-config

make && make install


7、加入扩展

echo "extension = pdo_sqlsrv.so" >> /www/server/php/72/etc/php.ini 

8、根据步骤3开始安装sqlsrv扩展 http://pecl.php.net/package/sqlsrv (注意对应pdo_sqlsrv版本)

wget http://pecl.php.net/get/sqlsrv-5.8.1.tgz

加入sqlsrv.so扩展

echo "extension = sqlsrv.so" >> /www/server/php/72/etc/php.ini

9、重启PHP

/etc/init.d/php-fpm-72 reload 

10、检查是否安装成功

/www/server/php/72/bin/php -m|grep -i  sqlsrv 

安装成功如下图

phpinfo检查已安装驱动成功

<?php
phpinfo()
?>


测试文件下载:

<?php
$serverName = "127.0.0.1:1433"; //数据库IP及端口
$connectionOptions = array(
    "database" => "DBname", //数据库名称
    "uid" => "user", //用户名
    "pwd" => "pw" //密码
);

// Establishes the connection
$conn = sqlsrv_connect($serverName, $connectionOptions);
if ($conn === false) {
    die(formatErrors(sqlsrv_errors()));
}

// Select Query
$tsql = "SELECT @@Version AS SQL_VERSION";

// Executes the query
$stmt = sqlsrv_query($conn, $tsql);

// Error handling
if ($stmt === false) {
    die(formatErrors(sqlsrv_errors()));
}
?>

<h1> 环境安装成功!以下是数据库信息: </h1>

<?php
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
    echo $row['SQL_VERSION'] . PHP_EOL;
}

sqlsrv_free_stmt($stmt);
sqlsrv_close($conn);

function formatErrors($errors)
{
    // Display errors
    echo "Error information: <br/>";
    foreach ($errors as $error) {
        echo "SQLSTATE: ". $error['SQLSTATE'] . "<br/>";
        echo "Code: ". $error['code'] . "<br/>";
        echo "Message: ". $error['message'] . "<br/>";
    }
}
?>

参考微软官方文档:https://docs.microsoft.com/zh-cn/sql/connect/php/installation-tutorial-linux-mac?view=sql-server-ver15

声明:我的幸运年|版权所有,违者必究|如未注明,均为原创|本网站采用BY-NC-SA协议进行授权

转载:转载请注明原文链接 - CentOS 7.6下宝塔面板 PHP7.2安装sqlsrv扩展


Carpe Diem and Do what I like