Home Backend Development PHP Tutorial ADODB database packaging library_PHP tutorial

ADODB database packaging library_PHP tutorial

Jul 21, 2016 pm 03:58 PM
php pleasure to use dynamic Can Library Establish database most of program website want

PHP可以用最少的功夫以及最多的乐趣来建立动态的网站,要建立动态网站我们需要使用数据库来撷取登入帐号资讯、散布动态新闻、储存讨论区的文章。就以使用最通用的MySQL资料来说,你们公司已经完成了如此神奇的工作,让你们的网站比你们所能想像的还要出名。接著你们也发现MySQL无法应付实际的工作量了,是该更换数据库系统的时候了。

不幸地,在PHP中所有数据库的存取都有些微的不同。与MySQL连结你要使用 mysql_connect(),当你决定升级到OracleMicrosoft SQL Server时,你必须分别改用ocilogon() mssql_connect()。更糟糕的是不同连结所使用的参数也都不一样,有的数据库说po-tato(马铃薯的发音),别的数据库又说pota-to(马铃薯的另一个发音),喔…..天啊。

我们不要放弃
当你需要确保你程式的可携性的时候,一个叫做ADODB的数据库封包程序库已经出现了。它提供了共通的应用程序介面来跟所有支援的数据库沟通,因此你无须放弃!

ADODB是Active Data Object DataBase的缩写(很抱歉!玩电脑的有时候不是很有原创性)。ADODB目前支援MySQL、PostgreSQL、Oracle、Interbase、Microsoft SQL Server、Access、FoxPro、Sybase、ODBC及ADO,你可以从 http://php.weblogs.com/adodb下载 ADODB。

MySQL的例子
PHP中最通用的数据库是MySQL,所以我想你会喜欢下面的程序代码,它连结到localhostMySQL服务器,数据库名称是mydab,并且执行一个SQLselect命令查询,查询结果会一列列地印出来。

<font color="#666600">$db = <b>mysql_connect</b>("localhost", "root", "password");
<b>mysql_select_db</b>("mydb",$db);</font>
<font color="#660000">$result = <b>mysql_query</b>("SELECT * FROM employees",$db)</font><code><font color="#663300">;
if ($result === false) die("failed");</font></code> 
<font color="#006666"><b>while</b> ($fields =<b> mysql_fetch_row</b>($result)) {
 <b>for</b> ($i=0, $max=sizeof($fields); $i < $max; $i++) {
    <B>print</B> $fields[$i].' ';
 }
 <B>print</B> "<br>n";
}</font> 
Copy after login

上列的程序代码用颜色标出分段,第一段是连结的部分,第二段是执行SQL命令,最後一段则是显示栏位,while回圈扫描结果的每一列,而for回圈扫描到每列的栏位。

接下来是以ADODB的程序代码得到同样的结果:

<font color="#666600"><b> include("adodb.inc.php");</b>
 $db = <b>NewADOConnection</b>('mysql');
 $db-><b>Connect</b>("localhost", "root", "password", "mydb");</font>
 <font color="#663300">$result = $db-><b>Execute</b>("SELECT * FROM employees");
 <code>if ($result === false) die("failed");</code></font> 
 <font color="#006666"><b>while</b> (!$result->EOF) {
  <b>for</b> ($i=0, $max=$result-><b>FieldCount</b>(); $i < $max; $i++)
      <B>print</B> $result->fields[$i].' ';
  $result-><b>MoveNext</b>();
  <b>print</b> "<br>n";
 }</font> 
Copy after login

现在改成指向Oracle数据库,程序代码只要修改第二行成为 NewADOConnection('oracle'),让我们看一下完整的程序代码...

与数据库连结

<font color="#666600"><b>include("adodb.inc.php");</b>
$db = <b>NewADOConnection</b>('mysql');
$db-><b>Connect</b>("localhost", "root", "password", "mydb");</font>
Copy after login

连结的程序代码比起原来MySQL的程序代码有老练一些,因为我们正是需要更老练些。在ADODB我们使用面向对象的方法来管理多样数据库的复杂性,我们用不同类型(class)来控制不同数据库。假如你不熟悉面向对象程式设计,别担心!所有的复杂事情都隐藏在NewADOConnection()函数之後。

为了节省记忆体,我们只载入与你所连结数据库相关的PHP程序代码,我们透过呼叫NewADOConnection(databasedriver)来完成这件事,合法的数据库驱动程式包含mysql,mssql,oracle,oci8,postgres,sybase,vfp,access,ibase以及许多其他的驱动程式。

接著我们透过呼叫NewADOConnection(),来从连结类型产生一个新的物件实体,最後我们使用$db->Connect()来连结数据库。

执行SQL命令

<font color="#663300"> <p>$result = $db-><b>Execute</b>("SELECT * FROM employees");<br>if ($result === false) die("failed");</p></font>

直接传送SQL命令到服务器,当成功执行之後,Execute()将传回一个recordset物件,你可以如同上面所列来检查$result。

一个初学者容易混淆的议题是,在ADODB有两种类型的物件,连结物件以及recordset物件,我们何时用这些物件呢?

连结物件($db)是负责连结数据库,格式化你的SQL查询。而recordset物件($result)则是负责撷取结果并将回应资料规格化成文字或阵列。

唯一我需要增加的事情是,ADODB提供许多有用的函数来让INSERT及UPDATE命令更容易些,这点我们在进阶的章节会提到。

撷取资料

<font color="#006666"><b>while</b> (!$result->EOF) {
  <b>for</b> ($i=0, $max=$result-><b>FieldCount</b>(); $i < $max; $i++)
    <B>print</B> $result->fields[$i].' ';
  $result-><b>MoveNext</b>();
  <b>print</b> "<br>n";
}</font>
Copy after login

前面取得资料的范例很像从档案读资料,在每一行我们首先检查是否到了档案的结尾(EOF),若还没到结尾,回圈扫过每列中的栏位,然後移到下一行(MoveNext)接著重复同样的事情。

$result->fields[]阵列是由PHP数据库延伸系统所产生的,有些数据库延伸系统并不会以栏位名称建立该阵列的索引,要强迫以名称排序索引该阵列,使用$ADODB_FETCH_MODE的通用变数。

	$<b>ADODB_FETCH_MODE</b> = ADODB_FETCH_NUM;
	$rs1 = $db->Execute('select * from table');
	$<b>ADODB_FETCH_MODE</b> = ADODB_FETCH_ASSOC;
	$rs2 = $db->Execute('select * from table');
	print_r($rs1->fields); // shows <i>array([0]=>'v0',[1] =>'v1')</i>
	print_r($rs2->fields); // shows <i>array(['col1']=>'v0',['col2'] =>'v1')</i>
Copy after login

如同你所见的上面例子,两个recordset储存并使用不同的取用模式,当recordset由Execute()产生後再设定$ADODB_FETCH_MODE。

ADOConnection

连结到数据库的物件,执行SQL命令并且有一组工具函数来标准格式化SQL命令,比如关联与日期格式等命令。

其他有用的函数

$recordset->Move($pos)卷动目前的资料列,ADODB支援整个数据库往前卷动,有一些数据库并不支援往後的卷动,这倒不会是个问题,因为你能够用暂存纪录到快取来模拟往後卷动。

$recordset->RecordCount()传回SQL命令存取到的纪录笔数,有些数据库会因为不支援而传回-1。

$recordset->GetArray()以阵列的方式传回结果。

rs2html($recordset)函数将传进的recordset转为HTML的表格格式。下例中以粗体字显示相关用法:

  include('adodb.inc.php'); 
  <b>include('tohtml.inc.php');</b> /* includes the rs2html function */
  $conn = &ADONewConnection('mysql'); 
  $conn->PConnect('localhost','userid','password','database');
  $rs = $conn->Execute('select * from table');
 <b> rs2html($rs)</b>; /* recordset to html table */ 
Copy after login

还有许多其他有用的函数列示在文件之中,可从下列网址查得 http://php.weblogs.com/adodb_manual

进阶题材

新增及更新

假设你要新增下列资料到数据库中。

ID = 3
TheDate=mktime(0,0,0,8,31,2001) /* 31st August 2001 */
Note= sugar why don't we call it off

当你改用别的数据库,可能就没办法新增资料。

第一个问题是,每一个数据库各自有不同的内定日期格式,MySQL使用 YYYY-MM-DD 格式,而其他数据库则有不同的内定格式,ADODB提供DBDate()函数来转换不同数据库之间的日期内定格式。

次一个问题是单引号(don't)的表示法,在MySQL可以直接使用单引号(don't),但在其他数据库如Sybase、Access、 Microsoft SQL Server,则用两个单引号表示(don''t),qstr()函数可以解决此问题。

我们如何使用这些函数?就像这样:

$sql = "INSERT INTO table (id, thedate,note) values (" 
  . $<b>ID</b> . ','
  . $db->DBDate($<b>TheDate</b>) .','
  . $db->qstr($<b>Note</b>).")";
$db->Execute($sql);
Copy after login

ADODB还有$connection->Affected_Rows()函数,传回受最後update或delete命令影响的资料列数,及$recordset->Insert_ID()函数,传回最後因insert命令而自动产生的资料列编号,预先提醒大家,没有任何数据库有提供这两个函数。

MetaTypes

你可以得到关於栏位的更多资讯,透过recordset的方法FetchField($fieldoffset)传回物件的3个属性:name,type,max_length。

举例说明:

$recordset = $conn->Execute("select adate from table");
$f0 = $recordset->FetchField(0);
Copy after login

结果$f0->name的内容是'adata',$f0->type将是'date',假如max_length不知道,其内容将会是-1。

处理不同数据库的一个问题是,每一个数据库对於相同的资料型态会有不同的称呼,比如timestamp型态在某数据库中称为datetime,而另一个数据库则称为time,所以ADODB提供MetaType($type,$max_length)函数来标准化下列的资料型态:

C: character and varchar types
X: text or long character (eg. more than 255 bytes wide).
B: blob or binary image
D: date
T: timestamp
L: logical (boolean)
I: integer
N: numeric (float, double, money)

在前面的例子中,

<p>$recordset = $conn->Execute("select adate from table");<br>$f0 = $recordset->FetchField(0);<br>$type = $recordset->MetaType($f0->type, $f0->max_length);<br>print $type; /* should print 'D'</p> */

Select命令的Limit及Top支援

ADODB有个$connection->SelectLimit($sql,$nrows,$offset)函数让你撷取recordset的部分集合,这是采用Microsoft产品中的SELECT TOP用法,及PostgreSQL与MySQL中的SELECT...LIMIT用法的优点,即使原来的数据库并没有提供此用法,本函数也模拟提供该使用方式。

快取支援

ADODB允许你在你的档案系统中暂存recordset的资料,并且在$connection->CacheExecute($secs2cache,$sql)及 $connection->CacheSelectLimit($secs2cache,$sql,$nrows,$offset)等设定的时间间隔到达之後,才真正去做数据库的查询以节省时间。

PHP4 Session支援

ADODB也支援PHP4 session handler,你可以存放你的session变数在数据库中,相关功能讯息请参考 http://php.weblogs.com/adodb-sessions

鼓励商业使用

If you plan to write commercial PHP application software for sale, you can also use ADODB. We publish ADODB under the GPL, which means you can legally reference it in commercial application software and retain ownership of your program code. Commercial use of ADODB is strongly encouraged, and we are using it internally for this reason.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/317532.htmlTechArticlePHP can build dynamic websites with the least effort and the most fun. To build dynamic websites we need to use a database To retrieve login account information, distribute dynamic news, save discussions...
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

MySQL: Simple Concepts for Easy Learning MySQL: Simple Concepts for Easy Learning Apr 10, 2025 am 09:29 AM

MySQL is an open source relational database management system. 1) Create database and tables: Use the CREATEDATABASE and CREATETABLE commands. 2) Basic operations: INSERT, UPDATE, DELETE and SELECT. 3) Advanced operations: JOIN, subquery and transaction processing. 4) Debugging skills: Check syntax, data type and permissions. 5) Optimization suggestions: Use indexes, avoid SELECT* and use transactions.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

Explain the match expression (PHP 8 ) and how it differs from switch. Explain the match expression (PHP 8 ) and how it differs from switch. Apr 06, 2025 am 12:03 AM

In PHP8, match expressions are a new control structure that returns different results based on the value of the expression. 1) It is similar to a switch statement, but returns a value instead of an execution statement block. 2) The match expression is strictly compared (===), which improves security. 3) It avoids possible break omissions in switch statements and enhances the simplicity and readability of the code.

What is Cross-Site Request Forgery (CSRF) and how do you implement CSRF protection in PHP? What is Cross-Site Request Forgery (CSRF) and how do you implement CSRF protection in PHP? Apr 07, 2025 am 12:02 AM

In PHP, you can effectively prevent CSRF attacks by using unpredictable tokens. Specific methods include: 1. Generate and embed CSRF tokens in the form; 2. Verify the validity of the token when processing the request.

See all articles