ADODB database packaging library_PHP tutorial
PHP可以用最少的功夫以及最多的乐趣来建立动态的网站,要建立动态网站我们需要使用数据库来撷取登入帐号资讯、散布动态新闻、储存讨论区的文章。就以使用最通用的MySQL资料来说,你们公司已经完成了如此神奇的工作,让你们的网站比你们所能想像的还要出名。接著你们也发现MySQL无法应付实际的工作量了,是该更换数据库系统的时候了。
不幸地,在PHP中所有数据库的存取都有些微的不同。与MySQL连结你要使用 mysql_connect(),当你决定升级到Oracle或Microsoft 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,所以我想你会喜欢下面的程序代码,它连结到localhost的MySQL服务器,数据库名称是mydab,并且执行一个SQL的select命令查询,查询结果会一列列地印出来。
<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 print $fields[$i].' '; } <b>print</b> "<br>n"; }</font>
上列的程序代码用颜色标出分段,第一段是连结的部分,第二段是执行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 print $result->fields[$i].' '; $result-><b>MoveNext</b>(); <b>print</b> "<br>n"; }</font>
现在改成指向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>
连结的程序代码比起原来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 print $result->fields[$i].' '; $result-><b>MoveNext</b>(); <b>print</b> "<br>n"; }</font>
前面取得资料的范例很像从档案读资料,在每一行我们首先检查是否到了档案的结尾(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>
如同你所见的上面例子,两个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 */
还有许多其他有用的函数列示在文件之中,可从下列网址查得 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);
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);
结果$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.

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.

In PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

Key players in HTTP cache headers include Cache-Control, ETag, and Last-Modified. 1.Cache-Control is used to control caching policies. Example: Cache-Control:max-age=3600,public. 2. ETag verifies resource changes through unique identifiers, example: ETag: "686897696a7c876b7e". 3.Last-Modified indicates the resource's last modification time, example: Last-Modified:Wed,21Oct201507:28:00GMT.

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP is a server-side scripting language used for dynamic web development and server-side applications. 1.PHP is an interpreted language that does not require compilation and is suitable for rapid development. 2. PHP code is embedded in HTML, making it easy to develop web pages. 3. PHP processes server-side logic, generates HTML output, and supports user interaction and data processing. 4. PHP can interact with the database, process form submission, and execute server-side tasks.

PHP has shaped the network over the past few decades and will continue to play an important role in web development. 1) PHP originated in 1994 and has become the first choice for developers due to its ease of use and seamless integration with MySQL. 2) Its core functions include generating dynamic content and integrating with the database, allowing the website to be updated in real time and displayed in personalized manner. 3) The wide application and ecosystem of PHP have driven its long-term impact, but it also faces version updates and security challenges. 4) Performance improvements in recent years, such as the release of PHP7, enable it to compete with modern languages. 5) In the future, PHP needs to deal with new challenges such as containerization and microservices, but its flexibility and active community make it adaptable.

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version
Useful JavaScript development tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version
Recommended: Win version, supports code prompts!

Zend Studio 13.0.1
Powerful PHP integrated development environment