Home Backend Development PHP Tutorial PHP中 ADOdb 类库介绍(一)_PHP

PHP中 ADOdb 类库介绍(一)_PHP

Jun 01, 2016 pm 12:34 PM
introduce use database

前言
为什么要使用数据库类库?
初学者 (甚至一些非初学者)常常犯的错误,就是在开发应用程序的时候,缺乏对未来的考虑。假如有一天,你的程序需要使用其它的数据库,难道你还需要重新写一篇针对于这个版本数据库的程序吗?这不是不可能发生的,尤其是当目前的数据库可能不适合你当前的需要的时候。 但是当你做这一切的时候 ,你会发现绝非你想像的那样容易:每一个 DBMS 有不同的函数。举例来说:在 Mysql 中连接数据库的函数为 mysql_connect(),而在MSSQL却是 mssql_connect()。重新查看你所有的代码,然后修改所有操作数据库的函数和查询语法,这绝不是一项简单的工作。程序会经常的被捆绑到了错误的数据库上,以至无法在运行时达到最优性能。数据库类库就是这样产生的。它允许你通过同样的代码来操作不同的数据库。一个设计良好的数据库类库可以完美的改变这一切。它允许你通过极小的修改,就能转接到其他数据库:无论你要连接什么数据库管理系统,只要使用同一个的函数,和不同的参数。举例来说, 在 ADOdb 中,只需简单地将 $db = NewADOConnection('access ') 修改为$db = NewADOConnection('mysql'),这样,你就轻松的把你的程序从 Access 数据库转移到了 Mysql 数据库中。现在网络上已经有了很多这样的数据库类库,比如Pear,PHPlib,我也已经在工作中使用它们了,也许你也曾经用过。但本文仅将重点放在我所特别关注的 ADOdb。本文我只简要地作一个介绍,使你能够马上运用它来开发你的下一个项目。以后的文章中我们将会循序渐进的对它进入更深入的了解。
目前,ADOdb 支持的数据库包括 MySQL, PostgreSQL,Interbase,Firebird,Informix,Oracle,MS SQL 7,Foxpro,Access,ADO,Sybase,FrontBase,DB2 和 generic ODBC。
ADOdb 的安装
安装 ADOdb 是一件极期容易的事,相信聪明的你一定不会感到吃力。
首先, 确定你正在运行的 PHP 是 4.0.4 版或更新版。 如果不是,我强列建议你升级!
从 PHP Everywhere 站点下载 .zip 或 .tgz 文件,解压缩到你所选的路径下。
这个路径不应在网页目录(WWWTREE,译者注:如果你的网页是在/www/下,那么,这个目录就不应为/www/here)下!虽然ADOdb的包含文件已经使用了 .inc.php 的扩展名 ,使得服务器即使是在最糟糕的配置下,也不会将这些.inc文件通过明文方式在浏览器中显示出来,但是我们向来不提倡将库函数文件放在网页目录下的行为。然后把下载下来的文件运行:tar -zxvf adodb350.tgz 解压,在Windows下你可以使用一个你喜欢的解压软件来操作,这样,你会得到一个 adodb 的目录其下包括了许多子目录。
测试你的安装
好了,让我们来测试一下你的安装吧。 通过在脚本中添加下列三行代码来测试你的安装是否成功。注意要把代码中的参数修改成你自己的。
include("$adodb_path/adodb.inc.php"); // includes the adodb library
$db = NewADOConnection('$database_type'); // A new connection
$db->Connect("$host", "$user", "$password", "$database_name");
现在你已经拥有一个数据库连接对象 $db 了。 你也可以使用 ADONewConnection 来替换 NewADOConnection —— 这两个是同一函数的不同的名字。 连接的数据库变量 $database_type 需要针对你的实际情况改成你所需要的。可以使用以下列表中的一个(括号内的为描述部分,不要在代码中使用):

access (Microsoft Access/Jet)
ado (Generic ADO, the base for all the other ADO drivers)
ado_access (Microsoft Access/Jet using ADO)
ado_mssql (Microsoft SQL Server using ADO)
db2 (DB2)
vfp (Microsoft Visual FoxPro)
fbsql (FrontBase)
ibase (Interbase 6 or before)
firebird (Firebird)
informix72 (Informix databases before Informix 7.3)
informix (Informix)
maxsql (MySQL with transaction support)
mssql (Microsoft SQL Server 7)
mssqlpo (Portable mssql driver)
mysql (MySQL without transaction support)
mysqlt (MySQL with transaction support, identical to maxmysql)
oci8 (Oracle 8/9)
oci805 (Oracle 8.0.5)
oci8po (Oracle 8/9 portable driver)
odbc (Generic ODBC, the base for all the other ODBC drivers)
odbc_mssql (MSSQL via ODBC)
odbc_oracle (Oracle via ODBC)
oracle (Oracle 7)
postgres (PostgreSQL)
postgres64 (PostgreSQL 6.4)
postgres7 (PostgreSQL 7, currently identical to postgres )
sqlanywhere (Sybase SQL Anywhere)
sybase (Sybase)
如果你的链接代码出现了错误的提示,那么你首先要检查的地方就是在路径或连接的变量上。在你责备 ADOdb 之前,请确定你是已经正确的使用那些变量。(很多朋友常花太多时间去修正这些显而易见的错误。) 如果连接没有任何错误提示,那么我们现在已经可以在我们的项目中来使用 ADodb 了。
通过你的脚本连接到数据库
把上边的代码加入到你的代码前,让我们先退一步。我们最好能把上边的代码用我们自己的方法来封装起来。这样可以使你的程序变得更灵活、更具移植性。如果你直接把上面的代码插入到你的项目的每个文件中,如果将来项目的路径改变了,将会很容易产生错误,如果你的密码改变了,你可能需要对你所有的脚本进行修改,这样将会影响我们使用库函数的初衷。并且,因为你的密码信息是在WEBTREE下的,这将产生隐患。我推荐将密码信息放在一个独立的包含文件中,比如在 ADOdb 安装目录下的某个地方。如果你要在其他服务器上运行你的程序时,你就不能保证目录结构会是相同的,所以,你要确保这个路径是正确的。我建议使用PHP 的自动包含功能来自动地包含这个文件。

include("$adodb_path/db_values.inc.php");
include("$adodb_path/adodb.inc.php");
$db = NewADOConnection('$database_type');
$db->Connect("$host", "$user", "$password", "employees");

如果你也想要使用持久连接, 不是每次创造一个新的连接(这使许多WEB应用程序得到了加速,但是要注意有些数据库是不支持的)。可以使用 PConnect 替换掉 Connect。
文件 db_values.inc.php 是我们的数据库信息文件,内容为(你需要把下面代码中的变量改成你自己的):
$database_type="mysql";
$host = "localhost"; // 本地数据库
$user = "ian"
$password = "let_me_in"
?>

你可以在 php.ini 配置中设定自动包含我们的配置文件,具体操作可以修改 PHP.ini 的下述行:
; Automatically add files before or after any PHP document.
auto_prepend_file = /usr/local/build/apache/www/tool_lib/defaults.inc
auto_append_file =


文件 defaults.inc 包含了 $adbdb_path 的值:

$adodb_path = "/usr/local/build/apache/www/tool_lib/";
?>

还有其他方式来实现它,但是我发现这种方法在移植时,可以相对地减少复杂度。

从一个数据库中进行选择(SELECT)操作
当同时使用开发良好的库函数,和PHP自身提供的函数时,可以有多种方法来访问数据库。用什么方法,完全取决于你自己的喜好。
这里是一个简单的例子:
$sql = "SELECT surname, age FROM employees";
$rs = &$db->Execute($sql);
if (!$rs) {
print $db->ErrorMsg(); // Displays the error message if no results could be returned
}
else {
while (!$rs->EOF) {
  print $rs->fields[0].' '.$rs->fields[1].'
';
   // fields[0] is surname, fields[1] is age
  $rs->MoveNext();  //  Moves to the next row
}
}


在上例中,$rs->fields 是一个包含返回值的数组。数组索引被赋予了初始的数字,你也可以按下面的方法来指定其索引:
$sql = "SELECT surname, age FROM employees";
$db->SetFetchMode(ADODB_FETCH_ASSOC); // Return associative array
$rs = &$db->Execute($sql);
if (!$rs) {
print $db->ErrorMsg(); // Displays the error message if no results could be returned
}
else {
while (!$rs->EOF) {
  print $rs->fields['surname']." ".$rs->fields['age']."
";
  $rs->MoveNext();  //  Moves to the next row
}  // end while
} // end else


对结果浏览的另一个可选的方法是将每条记录作为一个对象返回。 ADOdb 有一个 FetchNextObject() 的函数来实现这一功能,指针会自动地移到下一条记录。
$sql = "SELECT surname, age FROM employees";
$db->SetFetchMode(ADODB_FETCH_ASSOC); // Return associative array
$rs = &$db->Execute($sql);
if (!$rs) {
print $db->ErrorMsg(); // Displays the error message if no results could be returned
}
// loop through results
while ($row = $rs->FetchNextObject()) {
// The field names need to be uppercase
print $row->SURNAME." ".$row->AGE."
";
}


插入、更新记录
基本的 INSERT 操作方便、快捷, 拥有与SELECT一样的语法。
$sql = "INSERT INTO employees (surname, age) values ('Clegg','43')";
if (!($db->Execute($sql))) {
print 'Error inserting: '.$db->ErrorMsg().'
';
}


库函数真正的优点,在于它允许你通过相同的语法将记录放入不同的数据库之内,这在以前是绝对不可能的。通常有两种发生的情形。
第一种,引号。所有的引号需要用脱字符(即`符号,键位在Tab键的上边)代替,否则会引起语法错误。但是一些数据库使用一个单引号,另外一些则使用两个单引号。所以,你应当使用 ADOdb 中的 qstr() 而不是 PHP 中的 addslashes()。这样,返回值就将与你所使用的数据库相吻合了。
第二种,日期。许多数据库接受跟他们的日期类型不一致的、不兼容的格式。 ADOdb 有一个 DBDate() 函数,可以将 Unix 的 timestamp, 或 ISO(Y-m-d) 格式转换成任意格式,以此来满足你的数据库的需求。 见下例:
$employee_surname = $db->qstr("d'Angelo");
$arrival_time = $db->DBDate(time());
// The above two functions also add the enclosing quotes, so, $arrival_time, not '$arrival_time'
$sql = "INSERT INTO employee_arrival (arrival_time,surname) values ($arrival_time,$employee_surname)";
if (!($db->Execute($sql))) {
print 'Error inserting: '.$db->ErrorMsg().'
';
}

你可以以完全相同的方式更新数据库,举例来说:
$sql = "UPDATE employees SET age='44' WHERE id='121')";
if (!($db->Execute($sql))) {
print 'Error updating: '.$db->ErrorMsg().'
';
}

以上仅仅是 Adodb 的一些基本操作 —— 下次我们将会关注一些 ADOdb 提供的比较深层次的东西。 如果我已经使你胃口大开,而且你已经不能再等待, 我建议你去PHP Everywhere看一下,这个站点是ADOdb的专业站点,里面有很多有用的帮助信息。
本文原文地址: http://www.databasejournal.com/features/php/article.php/2222651

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)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1266
29
C# Tutorial
1239
24
BTCC tutorial: How to bind and use MetaMask wallet on BTCC exchange? BTCC tutorial: How to bind and use MetaMask wallet on BTCC exchange? Apr 26, 2024 am 09:40 AM

MetaMask (also called Little Fox Wallet in Chinese) is a free and well-received encryption wallet software. Currently, BTCC supports binding to the MetaMask wallet. After binding, you can use the MetaMask wallet to quickly log in, store value, buy coins, etc., and you can also get 20 USDT trial bonus for the first time binding. In the BTCCMetaMask wallet tutorial, we will introduce in detail how to register and use MetaMask, and how to bind and use the Little Fox wallet in BTCC. What is MetaMask wallet? With over 30 million users, MetaMask Little Fox Wallet is one of the most popular cryptocurrency wallets today. It is free to use and can be installed on the network as an extension

iOS 18 adds a new 'Recovered' album function to retrieve lost or damaged photos iOS 18 adds a new 'Recovered' album function to retrieve lost or damaged photos Jul 18, 2024 am 05:48 AM

Apple's latest releases of iOS18, iPadOS18 and macOS Sequoia systems have added an important feature to the Photos application, designed to help users easily recover photos and videos lost or damaged due to various reasons. The new feature introduces an album called "Recovered" in the Tools section of the Photos app that will automatically appear when a user has pictures or videos on their device that are not part of their photo library. The emergence of the "Recovered" album provides a solution for photos and videos lost due to database corruption, the camera application not saving to the photo library correctly, or a third-party application managing the photo library. Users only need a few simple steps

Detailed tutorial on establishing a database connection using MySQLi in PHP Detailed tutorial on establishing a database connection using MySQLi in PHP Jun 04, 2024 pm 01:42 PM

How to use MySQLi to establish a database connection in PHP: Include MySQLi extension (require_once) Create connection function (functionconnect_to_db) Call connection function ($conn=connect_to_db()) Execute query ($result=$conn->query()) Close connection ( $conn->close())

How to handle database connection errors in PHP How to handle database connection errors in PHP Jun 05, 2024 pm 02:16 PM

To handle database connection errors in PHP, you can use the following steps: Use mysqli_connect_errno() to obtain the error code. Use mysqli_connect_error() to get the error message. By capturing and logging these error messages, database connection issues can be easily identified and resolved, ensuring the smooth running of your application.

Introduction to the online score checking platform (convenient and fast score query tool) Introduction to the online score checking platform (convenient and fast score query tool) Apr 30, 2024 pm 08:19 PM

A fast score query tool provides students and parents with more convenience. With the development of the Internet, more and more educational institutions and schools have begun to provide online score check services. To allow you to easily keep track of your child's academic progress, this article will introduce several commonly used online score checking platforms. 1. Convenience - Parents can check their children's test scores anytime and anywhere through the online score checking platform. Parents can conveniently check their children's test scores at any time by logging in to the corresponding online score checking platform on a computer or mobile phone. As long as there is an Internet connection, whether at work or when going out, parents can keep abreast of their children's learning status and provide targeted guidance and help to their children. 2. Multiple functions - in addition to score query, it also provides information such as course schedules and exam arrangements. Many online searches are available.

What is Bitget Launchpool? How to use Bitget Launchpool? What is Bitget Launchpool? How to use Bitget Launchpool? Jun 07, 2024 pm 12:06 PM

BitgetLaunchpool is a dynamic platform designed for all cryptocurrency enthusiasts. BitgetLaunchpool stands out with its unique offering. Here, you can stake your tokens to unlock more rewards, including airdrops, high returns, and a generous prize pool exclusive to early participants. What is BitgetLaunchpool? BitgetLaunchpool is a cryptocurrency platform where tokens can be staked and earned with user-friendly terms and conditions. By investing BGB or other tokens in Launchpool, users have the opportunity to receive free airdrops, earnings and participate in generous bonus pools. The income from pledged assets is calculated within T+1 hours, and the rewards are based on

Detailed introduction of Samsung S24ai functions Detailed introduction of Samsung S24ai functions Jun 24, 2024 am 11:18 AM

2024 is the first year of AI mobile phones. More and more mobile phones integrate multiple AI functions. Empowered by AI smart technology, our mobile phones can be used more efficiently and conveniently. Recently, the Galaxy S24 series released at the beginning of the year has once again improved its generative AI experience. Let’s take a look at the detailed function introduction below. 1. Generative AI deeply empowers Samsung Galaxy S24 series, which is empowered by Galaxy AI and brings many intelligent applications. These functions are deeply integrated with Samsung One UI6.1, allowing users to have a convenient intelligent experience at any time, significantly improving the performance of mobile phones. Efficiency and convenience of use. The instant search function pioneered by the Galaxy S24 series is one of the highlights. Users only need to press and hold

How to use database callback functions in Golang? How to use database callback functions in Golang? Jun 03, 2024 pm 02:20 PM

Using the database callback function in Golang can achieve: executing custom code after the specified database operation is completed. Add custom behavior through separate functions without writing additional code. Callback functions are available for insert, update, delete, and query operations. You must use the sql.Exec, sql.QueryRow, or sql.Query function to use the callback function.

See all articles