centos7环境php7.x连接mssql数据库

一、加入微软的源

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

二、防止冲突先卸载原有版本(可选)

yum remove unixODBC 

三、安装驱动(三个都要装上,缺一不可)

yum install msodbcsql mssql-tools unixODBC-devel

四、下载pdo_sqlsrv扩展包  Microsoft Drivers for PHP for SQL Server

https://github.com/Microsoft/msphpsql/releases/tag/v5.2.0-RC
https://github.com/Microsoft/msphpsql/tags(全部连接)

五、下载的驱动解压放入 /www/server/php/74/lib/php/extensions/no-debug-non-zts-20190902 ,74代表php版本7.4,根据自己版本下载,如7.4下载7.4的

六、修改 php.ini 在后面添加

extension=php_sqlsrv_74_nts.so
extension=php_pdo_sqlsrv_74_nts.so

重新启动,然后phpinfo()  查看,存在 pdo_sqlsrv 说明php的sqlserver扩展安装成功

简单的测试代码:

<?php
      // 数据库用户
      $strDbUser = 'your_db_user';
      // 数据库密码
      $strDbPass = 'your_db_user_password';
      // 数据库服务器地址
      $strDbHost = 'your_sqlserver_address';
      // 数据库名称
      $strDbName = 'your_database_name';
      // 连接数据库的字符串定义
      $strDsn = "sqlsrv:Server=$strDbHost;Database=$strDbName;";
      // 生成pdo对象
      $objDB = new PDO($strDsn, $strDbUser, $strDbPass);
      foreach ($objDB->query('SELECT * FROM dbo.your_table_name') as $row) {
        var_dump($row);
        return;
      }
?>
//SQLSRV
    $serverName = "your_sqlserver_address";
    $connectionOptions = array("Database"=>"your_database_name", "Uid"=>"your_db_user", "PWD"=>"your_db_user_password");
    $conn = sqlsrv_connect($serverName, $connectionOptions);
    if( $conn === false ) {
     die(FormatErrors(sqlsrv_errors()));
    }
    
    $tsql = "select memb___id,memb__pwd,bloc_code,cz from MEMB_INFO where memb___id='lhpa'";
    $result= sqlsrv_query($conn, $tsql);
    $result= sqlsrv_fetch_array($result);
    echo $result['memb___id'];
    
    function FormatErrors($errors)
    {
        echo "Error information: <br/>";
     
        foreach ($errors as $error) {
            echo "SQLSTATE: ".$error['SQLSTATE']."<br/>";
            echo "Code: ".$error['code']."<br/>";
            echo "Message: ".$error['message']."<br/>";
        }
    }
?>

 

阅读剩余
THE END