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

Adodb的十个实例(清晰版)

Adodb的十个实例(清晰版)

作者:林辰时间:2025-02-20 13:45:02浏览:892

本文整理了Adodb数据库抽象层的十个核心使用实例。内容涵盖从基础的Access与MySQL连接、数据查询与字段格式化,到插入记录的SQL生成、调试模式开启以及多数据库同时连接等高级操作。此外,还详细演示了如何利用ADODB_Pager实现数据分页浏览,以及如何通过辅助函数将结果集导出为CSV或Tab分隔格式,并介绍了记录集过滤器RSFilter的应用方法。

本文目录展开

Adodb简介与核心优势分析

原本计划学习PEAR库,但鉴于网络上对Adodb的高度评价,最终决定转向学习该库。

根据网络资料总结,Adodb具备以下显著优势:

其一,执行速度比PEAR快约一倍;

其二,支持的数据库类型远超PEAR,甚至兼容ACCESS数据库;

其三,无需安装额外组件或依赖服务器特定支持,这对初学者而言至关重要。

若想了解Adodb详情或下载资源,可访问链接:http://www.phpe.net/class/106.shtml

如有朋友翻译了README全文或知晓译文来源,欢迎回复告知,谢谢。

教程部分

实例 1: 选择语句

任务目标:连接名为Northwind的Access数据库,并展示每条记录的前两个字段内容。

本实例中,我们创建一个ADOConnection对象,并通过PConnect方法建立持久连接。在查询时,调用该连接的Execute()函数,它将返回一个ADORecordSet对象(即游标),该对象在数组fields[]中保存当前行数据。利用MoveNext()方法可逐条遍历记录。

注意:本例未使用极具实用价值的SelectLimit函数,该函数可用于控制显示记录数量(如仅显示前10条),非常适合用于分页功能。

PHP代码示例:--------------------------------------------------------------------------------

include('adodb.inc.php'); #载入ADOdb
$conn = &ADONewConnection('access'); # 新建一个连接
$conn->PConnect('northwind'); # 连接到一个名为northwind的MS-Access数据库
$recordSet = &$conn->Execute('select * from products'); #从products数据表中搜索所有数据
if (!$recordSet)
print $conn->ErrorMsg(); //如果数据搜索发生错误显示错误信息
else
while (!$recordSet->EOF) {
print $recordSet->fields[0].' '.$recordSet->fields[1].'
';
$recordSet->MoveNext(); //指向下一个记录

} //列表显示数据

$recordSet->Close(); //可选
$conn->Close(); //可选
?>
-------------------------------------------------------------------------------- 

$recordSet在$recordSet->fields属性中以数字索引(从0开始)返回当前行的数组。通过MoveNext()函数移动至下一条记录。当遍历完所有记录后,EOF属性将被设置为true。若Execute()执行出错,recordset将返回false。

$recordSet->fields[]数组源自PHP的数据库扩展。部分扩展仅支持数字索引,不支持字段名索引。若需使用字段名索引,应调用SetFetchMode函数。无论采用何种索引方式,recordset均可由Execute()或SelectLimit()创建。

PHP代码示例:--------------------------------------------------------------------------------

$db->SetFetchMode(ADODB_FETCH_NUM);
$rs1 = $db->Execute('select * from table'); //采用数字索引
$db->SetFetchMode(ADODB_FETCH_ASSOC);
$rs2 = $db->Execute('select * from table'); //采用字段名索引
print_r($rs1->fields); # shows array([0]=>'v0',[1] =>'v1')
print_r($rs2->fields); # shows array(['col1']=>'v0',['col2'] =>'v1')--------------------------------------------------------------------------------

如需获取记录总数,可使用$recordSet->RecordCount()方法。若无当前记录,则返回-1。

实例 2: 高级选择与字段对象

搜索表格并显示前两个字段。若第二个字段为时间或日期格式,则将其转换为美国标准时间格式显示。

PHP代码示例:--------------------------------------------------------------------------------

include('adodb.inc.php'); ///载入adodb
$conn = &ADONewConnection('access'); //新建一个连接
$conn->PConnect('northwind'); //连接名为northwind的MS-Access数据库
$recordSet = &$conn->Execute('select CustomerID,OrderDate from Orders'); //从Orders表中搜索CustomerID和OrderDate两个字段
if (!$recordSet)
print $conn->ErrorMsg(); //如果数据库搜索错误,显示错误信息
else
while (!$recordSet->EOF) {
$fld = $recordSet->FetchField(1); //把第二个字段赋值给$fld
$type = $recordSet->MetaType($fld->type); //取字段值的格式
if ( $type == 'D' || $type == 'T')
print $recordSet->fields[0].' '.
$recordSet->UserDate($recordSet->fields[1],'m/d/Y').'

'; //如果字段格式为日期或时间型,使其以美国标准格式输出

else
print $recordSet->fields[0].' '.$recordSet->fields[1].'

'; //否则以原样输出

$recordSet->MoveNext(); //指向下一个记录
}
$recordSet->Close(); //可选
$conn->Close(); //可选
?>
-------------------------------------------------------------------------------- 

在此示例中,我们使用FetchField()函数检查第二个字段的格式。该函数返回一个包含三个属性的对象:

name: 字段名

type: 字段在其数据库中的真实格式

max_length:字段最大长度,部分数据库(如MYSQL)不返回此值,此时max_length等于-1。

我们使用MetaType()将字段的数据库原生格式转化为标准的字段类型标识:

C: 字符型字段,它应该可以在

标签下显示.

X: 文本型字段,存放比较大的文本,一般作用于

标签  
B: 块,二进制格式的大型对象,如图片  
D: 日期型字段  
T: 时间型字段  
L: 逻辑型字段 (布尔逻辑或bit-field)  
I: 整型字段  
N: 数字字段. 包括自动编号(autoincrement), 数字(numeric), 浮点数(floating point), 实数(real)和整数(integer).  
R: 连续字段. 包括serial, autoincrement integers.它只能工作于指定的数据库.  
如果metatype是日期或时戳类型的,我们用用户定义的日期格式UserDate()函数来输出,UserDate()用来转换PHP SQL 日期字符串格式到用户定义的格式,MetaType()的另一种用法是在插入和替换前确认数据有效性.  
实例 3: Inserting 
在订单数据表中插入一个包含日期和字符型数据的记录,插入之前必须先进行转换, eg: the single-quote in the word John's.  
PHP:-------------------------------------------------------------------------------- 
  
include('adodb.inc.php'); // 载入adodb
$conn = &ADONewConnection('access'); //新建一个连接
$conn->PConnect('northwind'); //连接到ACCESS数据库northwind
$shipto = $conn->qstr("John's Old Shoppe");
$sql = "insert into orders (customerID,EmployeeID,OrderDate,ShipName) ";
$sql .= "values ('ANATR',2,".$conn->DBDate(time()).",$shipto)";
if ($conn->Execute($sql) === false) {
print 'error inserting: '.$conn->ErrorMsg().'
';
} //如果插入不成功输出错误信息  
?>
-------------------------------------------------------------------------------- 
在这个例子中,我们看到ADOdb可以很容易地处理一些高级的数据库操作. unix时间戳 (一个长整数)被DBDate()转换成正确的Access格式, and the right escape character is used for quoting the John's Old Shoppe, which is John''s Old Shoppe and not PHP's default John's Old Shoppe with qstr().  
观察执行语句的错误处理. 如果Execute()发生错误, ErrorMsg()函数会返回最后一个错误提示. Note: php_track_errors might have to be enabled for error messages to be saved.  
实例 4: Debugging  
  
include('adodb.inc.php'); // 载入adodb
$conn = &ADONewConnection('access'); //新建一个连接
$conn->PConnect('northwind'); //连接到ACCESS数据库northwind
$shipto = $conn->qstr("John's Old Shoppe");
$sql = "insert into orders (customerID,EmployeeID,OrderDate,ShipName) ";
$sql .= "values ('ANATR',2,".$conn->FormatDate(time()).",$shipto)";
$conn->debug = true;
if ($conn->Execute($sql) === false) print 'error inserting';
?>
在上面这个例子里,我们设置了debug = true.它会在执行前显示所有SQL信息, 同时,它也会显示所有错误提示. 在这个例子里,我们不再需要调用ErrorMsg() . 要想显示recordset, 可以参考 rs2html()实例.  
也可以参阅 Custom Error Handlers 的部分内容。  
实例 5: MySQL and Menus  
连接到MySQL数据库agora, 并从SQL声明中产生一个下拉菜单 ,菜单的  选项显示为第一个字段, 返回值为第二个字段.  
PHP:-------------------------------------------------------------------------------- 
  
include('adodb.inc.php'); # load code common to ADOdb
$conn = &ADONewConnection('mysql'); //eate a connection
$conn->PConnect('localhost','userid','','agora'); //SQL数据库,数据库名为agora
$sql = 'select CustomerName, CustomerID from customers'; //搜索字段name用于显示,id用于返回值
$rs = $conn->Execute($sql);
print $rs->GetMenu('GetCust','Mary Rosli'); //显示菜单
?>
-------------------------------------------------------------------------------- 
在这里我们定义了一个名为GetCust的菜单,其中的'Mary Rosli'被选定. See GetMenu(). 我们还有一个把记录值返回到数组的函数: GetArray(), and as an associative array with the key being the first column: GetAssoc().  
实例 6: Connecting to 2 Databases At Once  
PHP:-------------------------------------------------------------------------------- 
  
include('adodb.inc.php'); # load code common to ADOdb
$conn1 = &ADONewConnection('mysql'); # create a mysql connection
$conn2 = &ADONewConnection('oracle'); # create a oracle connection
$conn1->PConnect($server, $userid, $password, $database);
$conn2->PConnect(false, $ora_userid, $ora_pwd, $oraname);
$conn1->Execute('insert ...');
$conn2->Execute('update ...');
?> //同时连接两个数据库
-------------------------------------------------------------------------------- 
7: Generating Update and Insert SQL  
ADOdb 1.31以上的版本支持两个新函数: GetUpdateSQL( ) 和 GetInsertSQL( ). This allow you to perform a "SELECT * FROM table query WHERE...", make a copy of the $rs->fields, modify the fields, and then generate the SQL to update or insert into the table automatically.  
我们来看看这两个函数在这个工作表中是如何执行的: (ID, FirstName, LastName, Created).  
Before these functions can be called, you need to initialize the recordset by performing a select on the table. Idea and code by Jonathan Younger jyounger#unilab.com.  
PHP:-------------------------------------------------------------------------------- 
  
#==============================================  
# SAMPLE GetUpdateSQL() and GetInsertSQL() code  
#==============================================  
include('adodb.inc.php');
include('tohtml.inc.php'); // 奇怪,这句似乎有没有都一样,哪位朋友知道原因请给个解释
#==========================  
# This code tests an insert  
$sql = "SELECT * FROM ADOXYZ WHERE id = -1"; #查找一个空记录 $conn = &ADONewConnection("mysql"); # create a connection
$conn->debug=1;
$conn->PConnect("localhost", "admin", "", "test"); # connect to MySQL, testdb
$rs = $conn->Execute($sql); # 获取一个空记录
$record = array(); # 建立一个数组准备插入
# 设置插入值$record["firstname"] = "Bob";  
$record["lastname"] = "Smith";
$record["created"] = time();
# Pass the empty recordset and the array containing the data to insert  
# into the GetInsertSQL function. The function will process the data and return  
# a fully formatted insert sql statement.# 插入前会格式化变量  
$insertSQL = $conn->GetInsertSQL($rs, $record);
$conn->Execute($insertSQL); # 在数据库中插入数据
#==========================  
# 下面这段程序演示修改数据,大致与上一段程序相同  
$sql = "SELECT * FROM ADOXYZ WHERE id = 1";
# Select a record to update  
$rs = $conn->Execute($sql); # Execute the query and get the existing record to update
$record = array(); # Initialize an array to hold the record data to update
# Set the values for the fields in the record  
$record["firstname"] = "Caroline";
$record["lastname"] = "Smith"; # Update Caroline's lastname from Miranda to Smith
# Pass the single record recordset and the array containing the data to update  
# into the GetUpdateSQL function. The function will process the data and return  
# a fully formatted update sql statement with the correct WHERE clause.  
# If the data has not changed, no recordset is returned  
$updateSQL = $conn->GetUpdateSQL($rs, $record);
$conn->Execute($updateSQL); # Update the record in the database
$conn->Close();
?>
-------------------------------------------------------------------------------- 
实例 8 Implementing Scrolling with Next and Previous  
下面的演示是个很小的分页浏览程序.  
PHP:-------------------------------------------------------------------------------- 
include_once('../adodb.inc.php');
include_once('../adodb-pager.inc.php');
session_start();
$db = NewADOConnection('mysql');
$db->Connect('localhost','root','','xphplens');
$sql = "select * from adoxyz ";
$pager = new ADODB_Pager($db,$sql);
$pager->Render($rows_per_page=5);--------------------------------------------------------------------------------
运行上面这段程序的结果如下:  
|< << >> >|  
ID First Name Last Name Date Created  
36 Alan Turing Sat 06, Oct 2001  
37 Serena Williams Sat 06, Oct 2001  
38 Yat Sun Sun Sat 06, Oct 2001  
39 Wai Hun See Sat 06, Oct 2001  
40 Steven Oey Sat 06, Oct 2001  
Page 8/10  
调用Render($rows)方法可以分页显示数据.如果你没有给Render()输入值, ADODB_Pager默认值为每页10个记录.  
你可以在 SQL里选择显示任意字段并为其定义名称:  
$sql = 'select id as "ID", firstname as "First Name",
lastname as "Last Name", created as "Date Created" from adoxyz';  
以上代码你可以在adodb/tests/testpaging.php 中找到, ADODB_Pager 对象在adodb/adodb-pager.inc.php中. 你可以给ADODB_Pager 的代码加上图像和改变颜色,你可以通过设置$pager->htmlSpecialChars = false来显示HTML代码.  
Some of the code used here was contributed by Iván Oliva and Cornel G.  
Example 9: Exporting in CSV or Tab-Delimited Format  
We provide some helper functions to export in comma-separated-value (CSV) and tab-delimited formats:  
PHP:-------------------------------------------------------------------------------- 
include_once('/path/to/adodb/toexport.inc.php');include_once('/path/to/adodb/adodb.inc.php');
$db = &NewADOConnection('mysql');$db->Connect($server, $userid, $password, $database);$rs = $db->Execute('select fname as "First Name", surname as "Surname" from table');
print "
";print rs2csv($rs); # return a string, CSV formatprint ''; $rs->MoveFirst(); # note, some databases do not support MoveFirstprint rs2tab($rs,false); # return a string, tab-delimited   
# false == suppress field names in first lineprint '';$rs->MoveFirst();rs2tabout($rs); # send to stdout directly (there is also an rs2csvout function)  
print "
";
$rs->MoveFirst();$fp = fopen($path, "w");
if ($fp) { rs2csvfile($rs, $fp); # write to file (there is also an rs2tabfile function)
fclose($fp);}--------------------------------------------------------------------------------
Carriage-returns or newlines are converted to spaces. Field names are returned in the first line of text. Strings containing the delimiter character are quoted with double-quotes. Double-quotes are double-quoted again. This conforms to Excel import and export guide-lines.  
All the above functions take as an optional last parameter, $addtitles which defaults to true. When set to false field names in the first line are suppressed.  
Example 10: Recordset Filters  
Sometimes we want to pre-process all rows in a recordset before we use it. For example, we want to ucwords all text in recordset.  
PHP:-------------------------------------------------------------------------------- 
include_once('adodb/rsfilter.inc.php');
include_once('adodb/adodb.inc.php');
// ucwords() every element in the recordset
function do_ucwords(&$arr,$rs)
{
foreach($arr as $k => $v) {
$arr[$k] = ucwords($v);
}
}
$db = NewADOConnection('mysql');
$db->PConnect('server','user','pwd','db');
$rs = $db->Execute('select ... from table');
$rs = RSFilter($rs,'do_ucwords');--------------------------------------------------------------------------------
The RSFilter function takes 2 parameters, the recordset, and the name of the filter function. It returns the processed recordset scrolled to the first record. The filter function takes two parameters, the current row as an array, and the recordset object. For future compatibility, you should not use the original recordset object. 
上一篇
PHP检查URL包含特定字符串的三种方法

在PHP开发中,判断URL是否包含特定子串是常见需求。本文介绍两种主要实现方式:利用strpos()函数查找首次出现位置及区分大小写的特性,以及使用substr_count()统计子串出现次数;此外还展示了基于正则表达式的preg_match()匹配方案。通过具体代码示例演示如何在不同场景下准确识别URL中的目标字符。

下一篇
在Zeus Web Server中配置PHP FastCGI远程响应支持

本文介绍如何在Unix环境下的Zeus Web Server中通过Remote Responders方式集成PHP,以获得比本地调用更高的扩展性和运行效率。主要步骤包括:根据PHP版本决定是否安装libfcgi库;编译启用--enable-fastcgi或--with-fastcgi参数的PHP;在Zeus控制台配置FastCGI远程响应器及URL Handler;最后创建并启动S05php脚本以管理持久化PHP进程。

相关文章

更多
ADODB类使用

ADODB为PHP提供跨数据库的抽象层,通过NewADOConnection创建对象并调用Connect方法连接MySQL、Oracle等多种数据库。核心概念包括负责执行SQL的ADOConnection对象与处理结果的Recordset对象。支持通过DBDate和qstr函数标准化日期与字符串,利用MetaType统一字段类型,并提供SelectLimit分页及CacheExecute缓存功能以优化性能。

2025.04.09 886
Smarty与ADODB结合实战:数据库连接、数据获取及模板渲染详解

本教程介绍如何在PHP项目中将Smarty模板引擎与ADODB数据库类库结合使用。通过修正前期代码错误,详细讲解ADODB的安装配置、DSN与传统连接方式、核心方法如GetArray和GetRow的使用,并展示index.php、news.php及newsList.php三个文件的具体实现,旨在简化二维数组构建过程,提升开发效率。

2025.07.01 782
PHP ADODB生成下拉列表框功能示例

本文介绍使用 PHP ADODB 库生成下拉列表框的实现方法。通过 conn.php 建立数据库连接,并在 select.php 中构建包含商品类别选项的表单元素。文中提供了相关代码片段及运行效果展示,帮助开发者快速集成该功能。

2025.02.11 699
ADODB:PHP跨数据库编程的统一解决方案

ADODB是一个为PHP设计的数据库封装程序库,旨在解决不同数据库系统(如MySQL、Oracle、SQL Server等)API差异导致的代码不可移植问题。它通过统一的面向对象接口屏蔽底层数据库细节,支持连接管理、SQL执行、结果集处理及日期格式标准化等功能,极大简化了多数据库环境下的开发工作并提升了应用的可维护性。

2025.12.08 628
基于Smarty与ADODB的PHP MVC开发模式实践

该文章总结了使用Smarty控制显示、通过case语句分发action并结合自定义class模块的PHP开发经验。这种MVC架构提升了代码复用率,便于协同开发,但在处理个性化查询时,控制器中直接调用DB类可能导致代码略显臃肿。作者建议根据功能独立性灵活组织代码结构。

2026.06.04 574
CodeIgniter集成Smarty与ADODB库的实现步骤

在CodeIgniter框架中集成Smarty模板引擎和ADODB数据库抽象层,需遵循特定的文件结构规范。通过在application/libraries目录下创建对应的类文件,并在application/init目录下编写初始化脚本,可实现两者的加载。实际使用中需注意文件路径的相对基准以及可能的重复实例化问题,以确保功能正常运行。

2026.06.30 512

专题推荐

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

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

PHP 定时任务配置与运行

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

Yii2 队列配置与常驻运行

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

PHP Session 过期时间设置方法

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

PHP URL 编码和解码方法

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

在线工具箱

更多
键码查询
键码查询

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

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

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

进制转换
进制转换

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

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

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

文件 Base64 转换
文件 Base64 转换

把文件转为 Base64 文本,也可将编码内容还原为文件,方便接口传输与调试。