极乐门资源网 Design By www.ioogu.com
本想学pear的,可是网上看到的几篇帖子对adodb的评价相当高,所以改学了这个。
ADODB的优点有这几个(网上说的,不是我说的):
1、速度比pear快一倍;
2、支持的数据库类型比pear多很多,甚至可以支持ACCESS;
3、无须安装,无须服务器支持(对新手来说,这点很重要吧)
不知道adodb是什么或是想下载adodb的朋友可以去这个链接看看:http://www.phpe.net/class/106.shtml
另外,如果哪位兄弟翻译了README的全文或知道哪里有译文请给我回个帖,谢谢。
Tutorial
Example 1: Select Statement
任务: 连接一个名为Northwind的Access数据库, 显示 每条记录 的前两个字段.
在这个实例里, 我们新建了一个ADOC连接(ADOConnection)对象, 并用它来连接一个数据库. 这个连接采用PConnect 方法, 这是一个持久 连接. 当我们要查询数据 库时, 我们可以随时调 用这个连接的Execute()函数. 它会返回一个ADORecordSet对象 which is actually a cursor that holds the current row in the array fields[]. 我们使用MoveNext()从一个记录转向下一个记录 .
NB: 有一 个非常实用的函数 SelectLimit在本例中没有用到, 它可以控制显示的记录数(如只显示前十条记录 ,可用作分页显示 ).
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].'<BR>';
$recordSet->MoveNext(); //指向下一个记录
} //列表显示数据
$recordSet->Close(); //可选
$conn->Close(); //可选
?>
--------------------------------------------------------------------------------
$recordSet在$recordSet->fields中返回当前数组, 对字段进行数字索引(从0开始). 我们用MoveNext() 函数移动到下一个记录 . 当数据库搜索到结尾时EOF property被 设置 为true. 如果Execute()发生错误 , recordset返回flase.
$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: Advanced Select with Field Objects
搜索表格,显示前两个字段. 如果第二个字段是时间或日期格式,则将其改为美国标准时间格式显示.
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').'<BR>'; //如果字段格式为日期或时间型,使其以美国标准格式输出
else
print $recordSet->fields[0].' '.$recordSet->fields[1].'<BR>'; //否则以原样输出
$recordSet->MoveNext(); //指向下一个记录
}
$recordSet->Close(); //可选
$conn->Close(); //可选
?>
--------------------------------------------------------------------------------
在这个例子里, 我们用FetchField()函数检查了第二个字段的格式. 它返回了一个包含三个变量的对象
name: 字段名
type: 字段在其数据库中的真实格式
max_length:字段最大长度,部分数据库不会返回这个值,比如MYSQL,这种情况下max_length值等于-1.
我们使用MetaType()把字段的数据库格式转化为标准的字段格式
C: 字符型字段,它应该可以在<input type="text">标签下显示.
X: 文本型字段,存放比较大的文本,一般作用于<textarea>标签
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().'<BR>';
} //如果插入不成功输出错误信息
?>
--------------------------------------------------------------------------------
在这个例子中,我们看到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声明中产生一个<select>下拉菜单 ,菜单的 <option> 选项显示为第一个字段, 返回值为第二个字段.
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 "<pre>";print rs2csv($rs); # return a string, CSV formatprint '<hr>'; $rs->MoveFirst(); # note, some databases do not support MoveFirstprint rs2tab($rs,false); # return a string, tab-delimited
# false == suppress field names in first lineprint '<hr>';$rs->MoveFirst();rs2tabout($rs); # send to stdout directly (there is also an rs2csvout function)
print "</pre>";
$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.
ADODB的优点有这几个(网上说的,不是我说的):
1、速度比pear快一倍;
2、支持的数据库类型比pear多很多,甚至可以支持ACCESS;
3、无须安装,无须服务器支持(对新手来说,这点很重要吧)
不知道adodb是什么或是想下载adodb的朋友可以去这个链接看看:http://www.phpe.net/class/106.shtml
另外,如果哪位兄弟翻译了README的全文或知道哪里有译文请给我回个帖,谢谢。
Tutorial
Example 1: Select Statement
任务: 连接一个名为Northwind的Access数据库, 显示 每条记录 的前两个字段.
在这个实例里, 我们新建了一个ADOC连接(ADOConnection)对象, 并用它来连接一个数据库. 这个连接采用PConnect 方法, 这是一个持久 连接. 当我们要查询数据 库时, 我们可以随时调 用这个连接的Execute()函数. 它会返回一个ADORecordSet对象 which is actually a cursor that holds the current row in the array fields[]. 我们使用MoveNext()从一个记录转向下一个记录 .
NB: 有一 个非常实用的函数 SelectLimit在本例中没有用到, 它可以控制显示的记录数(如只显示前十条记录 ,可用作分页显示 ).
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].'<BR>';
$recordSet->MoveNext(); //指向下一个记录
} //列表显示数据
$recordSet->Close(); //可选
$conn->Close(); //可选
?>
--------------------------------------------------------------------------------
$recordSet在$recordSet->fields中返回当前数组, 对字段进行数字索引(从0开始). 我们用MoveNext() 函数移动到下一个记录 . 当数据库搜索到结尾时EOF property被 设置 为true. 如果Execute()发生错误 , recordset返回flase.
$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: Advanced Select with Field Objects
搜索表格,显示前两个字段. 如果第二个字段是时间或日期格式,则将其改为美国标准时间格式显示.
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').'<BR>'; //如果字段格式为日期或时间型,使其以美国标准格式输出
else
print $recordSet->fields[0].' '.$recordSet->fields[1].'<BR>'; //否则以原样输出
$recordSet->MoveNext(); //指向下一个记录
}
$recordSet->Close(); //可选
$conn->Close(); //可选
?>
--------------------------------------------------------------------------------
在这个例子里, 我们用FetchField()函数检查了第二个字段的格式. 它返回了一个包含三个变量的对象
name: 字段名
type: 字段在其数据库中的真实格式
max_length:字段最大长度,部分数据库不会返回这个值,比如MYSQL,这种情况下max_length值等于-1.
我们使用MetaType()把字段的数据库格式转化为标准的字段格式
C: 字符型字段,它应该可以在<input type="text">标签下显示.
X: 文本型字段,存放比较大的文本,一般作用于<textarea>标签
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().'<BR>';
} //如果插入不成功输出错误信息
?>
--------------------------------------------------------------------------------
在这个例子中,我们看到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声明中产生一个<select>下拉菜单 ,菜单的 <option> 选项显示为第一个字段, 返回值为第二个字段.
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 "<pre>";print rs2csv($rs); # return a string, CSV formatprint '<hr>'; $rs->MoveFirst(); # note, some databases do not support MoveFirstprint rs2tab($rs,false); # return a string, tab-delimited
# false == suppress field names in first lineprint '<hr>';$rs->MoveFirst();rs2tabout($rs); # send to stdout directly (there is also an rs2csvout function)
print "</pre>";
$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.
标签:
Adodb的十个实例(清晰版)
极乐门资源网 Design By www.ioogu.com
极乐门资源网
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件!
如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
极乐门资源网 Design By www.ioogu.com
暂无Adodb的十个实例(清晰版)的评论...
稳了!魔兽国服回归的3条重磅消息!官宣时间再确认!
昨天有一位朋友在大神群里分享,自己亚服账号被封号之后居然弹出了国服的封号信息对话框。
这里面让他访问的是一个国服的战网网址,com.cn和后面的zh都非常明白地表明这就是国服战网。
而他在复制这个网址并且进行登录之后,确实是网易的网址,也就是我们熟悉的停服之后国服发布的暴雪游戏产品运营到期开放退款的说明。这是一件比较奇怪的事情,因为以前都没有出现这样的情况,现在突然提示跳转到国服战网的网址,是不是说明了简体中文客户端已经开始进行更新了呢?
更新日志
2024年12月31日
2024年12月31日
- 小骆驼-《草原狼2(蓝光CD)》[原抓WAV+CUE]
- 群星《欢迎来到我身边 电影原声专辑》[320K/MP3][105.02MB]
- 群星《欢迎来到我身边 电影原声专辑》[FLAC/分轨][480.9MB]
- 雷婷《梦里蓝天HQⅡ》 2023头版限量编号低速原抓[WAV+CUE][463M]
- 群星《2024好听新歌42》AI调整音效【WAV分轨】
- 王思雨-《思念陪着鸿雁飞》WAV
- 王思雨《喜马拉雅HQ》头版限量编号[WAV+CUE]
- 李健《无时无刻》[WAV+CUE][590M]
- 陈奕迅《酝酿》[WAV分轨][502M]
- 卓依婷《化蝶》2CD[WAV+CUE][1.1G]
- 群星《吉他王(黑胶CD)》[WAV+CUE]
- 齐秦《穿乐(穿越)》[WAV+CUE]
- 发烧珍品《数位CD音响测试-动向效果(九)》【WAV+CUE】
- 邝美云《邝美云精装歌集》[DSF][1.6G]
- 吕方《爱一回伤一回》[WAV+CUE][454M]