当前位置: 首页 > 编程文章 >

Zend Framework 配置 SQL Server 数据库连接及中文编码处理

Zend Framework 配置 SQL Server 数据库连接及中文编码处理

作者:苏景时间:2026-08-30 17:19:11浏览:181

本文介绍在 Zend Framework 中配置 SQL Server 数据库连接的具体步骤,包括修改 Abstract.php 中的 connect 方法以适配不同操作系统,以及更新 web.xml 配置文件。针对连接过程中可能出现的中文乱码问题,提供了基于 pdoType 判断的字符集转换函数实现方案,确保数据读写正常。

本文目录收起

Zend Framework 配置 SQL Server 数据库连接及中文编码处理

本示例详细说明了在 Zend 框架中启用 SQL Server 支持的具体实施方法,供开发者参考使用。

第一步需要调整 Zend/Db/Adapter/Pdo/Abstract.php 文件内的 connect 方法逻辑。


protected function _connect()
{
  // if we already have a PDO object, no need to re-connect.
  if ($this->_connection) {
    return;
  }
  // get the dsn first, because some adapters alter the $_pdoType
  $dsn = $this->_dsn();
  // check for PDO extension
  if (!extension_loaded('pdo')) {
    /**
     * [url=home.php?mod=space&uid=86763]@see[/url] Zend_Db_Adapter_Exception
     */
    require_once 'Zend/Db/Adapter/Exception.php';
    throw new Zend_Db_Adapter_Exception('The PDO extension is required for this adapter but the extension is not loaded');
  }
  // check the PDO driver is available
  if (!in_array($this->_pdoType, PDO::getAvailableDrivers())) {
    /**
     * @see Zend_Db_Adapter_Exception
     */
    require_once 'Zend/Db/Adapter/Exception.php';
    throw new Zend_Db_Adapter_Exception('The ' . $this->_pdoType . ' driver is not currently installed');
  }
  // create PDO connection
  $q = $this->_profiler->queryStart('connect', Zend_Db_Profiler::CONNECT);
  // add the persistence flag if we find it in our config array
  if (isset($this->_config['persistent']) && ($this->_config['persistent'] == true)) {
    $this->_config['driver_options'][PDO::ATTR_PERSISTENT] = true;
  }
  try {
    //print_r($this->_config);exit;
    if($this->_config['pdoType']=='sqlsrv'){
      $this->_connection = new PDO( "sqlsrv:Server=".$this->_config['host'].";Database = ".$this->_config['dbname'], $this->_config['username'], $this->_config['password']);
      $this->_connection->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
      $this->_connection->setAttribute( PDO::SQLSRV_ATTR_ENCODING, PDO::SQLSRV_ENCODING_UTF8 );
      $this->_profiler->queryEnd($q);
    }elseif ($this->_config['pdoType']=='dblib') {
      $this->_connection = new PDO(
        $dsn,
        $this->_config['username'],
        $this->_config['password'],
        $this->_config['driver_options']
      );
      $this->_profiler->queryEnd($q);
    }
    // set the PDO connection to perform case-folding on array keys, or not
    $this->_connection->setAttribute(PDO::ATTR_CASE, $this->_caseFolding);
    // always use exceptions.
    $this->_connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  } catch (PDOException $e) {
    /**
     * @see Zend_Db_Adapter_Exception
     */
    require_once 'Zend/Db/Adapter/Exception.php';
    throw new Zend_Db_Adapter_Exception($e->getMessage());
  }
}

根据运行环境是 Linux 还是 Windows,分别采用相应的连接策略。

在 mssql.php 文件中,将 protected $_pdoType 属性设置为 'sqlsrv'。


protected function _dsn()
{
    // baseline of DSN parts
    $dsn = $this->_config;
    // don't pass the username and password in the DSN
    unset($dsn['username']);
    unset($dsn['password']);
    unset($dsn['driver_options']);
    if (isset($dsn['port'])) {
      $seperator = ':';
      if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
        $seperator = ',';
      }
      $dsn['host'] .= $seperator . $dsn['port'];
      unset($dsn['port']);
    }
    // this driver supports multiple DSN prefixes
    // @see http://www.php.net/manual/en/ref.pdo-dblib.connection.php
    //print_r($dsn);exit;
    if (isset($dsn['pdoType'])) {
      switch (strtolower($dsn['pdoType'])) {
        case 'freetds':
        case 'sybase':
          $this->_pdoType = 'sybase';
          break;
        case 'mssql':
          $this->_pdoType = 'mssql';
          break;
        case 'sqlsrv':
          $this->_pdoType = 'sqlsrv';
          break;
        case 'dblib':
        default:
          $this->_pdoType = 'dblib';
          break;
      }
      unset($dsn['pdoType']);
    }
    // use all remaining parts in the DSN
    foreach ($dsn as $key => $val) {
      $dsn[$key] = "$key=$val";
    }
    $dsn = $this->_pdoType . ':' . implode(';', $dsn);
   // print_r($dsn);exit;
    return $dsn;
}

第三步是更新 ZF 项目中的 web.xml 数据库配置文件。



  PDO_MSSQL

    localhost
    sa
    123456
    testdb 
    sqlsrv
  


在实际操作过程中,可能会遇到中文字符显示为乱码的情况。


function convert2utf8($string)
{
    $config = $this->getCfg();
    $pdoType = $config->db->config->pdoType;
    if($pdoType == 'dblib'){
      return iconv("gbk","utf-8",$string);
    }elseif($pdoType == 'sqlsrv'){
      return mb_convert_encoding($string,"UTF-8","auto");
    }
}
function convert2gbk($string)
{
    $config = $this->getCfg();
    $pdoType = $config->db->config->pdoType;
    if($pdoType == 'dblib'){
      return iconv("utf-8","gbk",$string);
    }elseif($pdoType == 'sqlsrv'){
      return mb_convert_encoding($string,"GBK","auto");
    }
}
protected function &getCfg() {
    if ($this->cfg_ === null) {
      $registry = Zend_Registry::getInstance();
      $this->cfg_ = $registry->get('web_config');
    }
    return $this->cfg_;
} 

需依据不同的 PDO 类型执行对应的编码转换处理逻辑。

期望上述内容能为使用 Zend Framework 进行 PHP 开发的读者提供有益帮助。

上一篇
Laravel 5中try-catch捕获异常的命名空间问题及解决方案

在Laravel 5项目中,使用try-catch语句直接捕获Exception类往往失效。这是因为Laravel 5将控制器移至子命名空间,导致默认无法访问根命名空间的Exception类。解决方法是在文件头部引入use \Exception或在使用时显式指定\Exception。本文通过代码实例演示了错误与正确的写法,帮助开发者快速定位并解决该异常捕获失败的问题。

下一篇
PHP序列化机制详解:原理、钩子与Laravel应用

PHP序列化将对象转换为可存储或传输的字符串,便于数据库保存或网络发送。核心函数为serialize()和unserialize(),格式包含类型标识符如O:4:"User"。通过__sleep()和__wakeup()钩子可控制序列化属性及初始化逻辑。在Laravel中,SerializesModels特性仅序列化Eloquent模型标识符以减小负载,外部通信也可结合JSON标准使用json_encode/decode。

相关文章

更多
PHP使用PDO连接SQL Server示例分享

本文介绍如何在PHP环境中通过PDO扩展连接SQL Server数据库。主要步骤包括下载并安装PECL中的PDO_DBLIB库,配置php.d目录下的ini文件加载pdo_dblib.so模块,重启Apache服务后,通过修改PDO构造函数的DSN参数即可实现跨数据库类型的统一访问。

2026.11.18 207
PHP PDO 处理 SQLSTATE 23000:区分重复键与必填值缺失

在 PHP 使用 PDO MySQL 进行批量导入时,SQLSTATE 23000 既可能由唯一键重复(如 MySQL 1062)引起,也可能因必填字段为 NULL(如 MySQL 1048)触发。仅依赖 SQLSTATE 无法区分具体业务原因,需结合驱动错误码 errorInfo 中的第二位进行判断。通过记录详细错误信息并验证最终数据状态,可避免将缺失必填值的错误误判为重复数据而静默跳过。

2026.01.26 991
PHP数据库表操作的封装类及用法实例详解

本文介绍一个基于PDO的PHP数据库表操作封装类Table,支持插入、更新、删除、查询及分页等常用功能。该类通过链式调用简化SQL构建,适用于单表数据管理。文章详细演示了各类方法的参数设置与返回结果,并提供了完整的源代码链接供开发者参考使用。

2026.01.06 991
PHP PDOStatement::bindParam 详解:绑定参数与执行预处理语句

PDOStatement::bindParam 用于将 PHP 变量以引用方式绑定到预处理 SQL 语句的占位符,仅在 execute 调用时取值。该方法支持命名和问号占位符,可指定数据类型、长度及驱动选项,适用于输入、输出或输入输出参数的存储过程调用,有效防止 SQL 注入并提升查询性能。

2025.06.03 985
Zend Framework 中 Zend_Config 组件的多种配置读取方式详解

本文详细介绍 Zend Framework 中 Zend_Config 组件的四种主要数据读取方式。通过实例演示如何从 PHP 数组、PHP 代码文件、INI 格式文件以及 XML 文件中加载配置信息,并展示如何将配置对象转换为数组形式。这些方法涵盖了数据库连接参数等常见配置场景,帮助开发者灵活管理应用配置。

2026.06.16 984
PHP使用PDO从MySQL读取大量数据:关闭缓冲查询与生成器优化

本文介绍在PHP 5.6环境下,利用PDO连接MySQL 5.6处理大规模数据集时的内存优化方案。核心在于设置PDO::MYSQL_ATTR_USE_BUFFERED_QUERY为false以禁用结果集缓冲,配合yield生成器逐行迭代数据,从而将内存占用控制在极低水平(如0.34MB),成功处理超过25万行数据而避免内存溢出。

2026.01.01 977

专题推荐

更多
PHP 类与对象定义及继承

先看类声明、对象实例与属性访问。理解对象的创建和销毁后,再读继承、方法重载和关键字对照。已有代码遇到继承行为差异时,可进一步查看 final 方法与反射实例。

PHP 定时任务配置与运行

先确定任务运行间隔以及是否允许重叠。固定时间触发先看 Cron 案例,框架内和常驻服务再读对应示例。

Yii2 队列配置与常驻运行

先用一个最小任务跑通入队和消费,再检查 Web 与 Console 是否加载了相同的队列配置。确认命令能手动运行后再配置 Supervisor,最后验证进程重启时的处理情况。

PHP Session 过期时间设置方法

浏览器关闭、服务端回收和业务规定的闲置超时,可能在不同时间发生。对照配置项与应用层时间戳的做法,检查会话何时仍可读、何时应要求重新登录。

PHP URL 编码和解码方法

URL 路径片段和查询参数对空格的处理方式不同。先比较 urlencode 与 rawurlencode,再沿解码过程核对中文、加号和百分号,检查地址是否被重复编码或提前解码。

在线工具箱

更多
PDO 参数绑定代码生成
PDO 参数绑定代码生成

检查 SQL 命名或问号占位符与 JSON 参数是否匹配,生成使用原生预处理及 bindValue 的 PHP PDO 代码。

键码查询
键码查询

按下键盘按键时查看浏览器记录的键名和事件信息。

.env 配置检查
.env 配置检查

本地检查 .env 键值语法、引号、重复键及空值,预览解析结果,辅助排查 PHP 和 Laravel 环境配置。

进制转换
进制转换

转换二进制、十进制、十六进制等数值表示,辅助程序调试与进制学习。

HTML 标签安全清理
HTML 标签安全清理

清理 HTML 片段中的标签或危险内容,辅助整理待展示的文本。