ADODB類使用
Jun 13, 2016 pm 12:35 PM
MySQL的例子
PHP中最通用的數(shù)據(jù)庫是MySQL,所以我想你會喜歡下面的程序代碼,它連結(jié)到 localhost 的 MySQL 服務(wù)器,數(shù)據(jù)庫名稱是 mydab,并且執(zhí)行一個 SQL 的 select 指令查詢,查詢結(jié)果會一列列地印出來。
$db = mysql_connect("localhost", "root", "password");
mysql_select_db("mydb",$db);
$result = mysql_query("SELECT * FROM employees",$db);
if ($result === false) die("failed");
while ($fields = mysql_fetch_row($result)) {
?for ($i=0, $max=sizeof($fields); $i ??????? print $fields[$i].' ';
?}
?print "
n";
}
上列的程序代碼用顏色標出分段,第一段是連結(jié)的部分,第二段是執(zhí)行SQL指令,最后一段則是顯示字段,while循環(huán)掃描結(jié)果的每一列,而for循環(huán)掃描到每列的字段。
接下來是以ADODB的程序代碼得到同樣的結(jié)果:
?include("adodb.inc.php");
?$db = NewADOConnection('mysql');
?$db->Connect("localhost", "root", "password", "mydb");
?$result = $db->Execute("SELECT * FROM employees");
?if ($result === false) die("failed");?
?while (!$result->EOF) {
??? for ($i=0, $max=$result->FieldCount(); $i ?????????? print $result->fields[$i].' ';
??? $result->MoveNext();
??? print "
n";
?}
現(xiàn)在改成指向Oracle數(shù)據(jù)庫,程序代碼只要修改第二行成為 NewADOConnection('oracle'),讓我們看一下完整的程序代碼...
與數(shù)據(jù)庫連結(jié)
include("adodb.inc.php");
$db = NewADOConnection('mysql');
$db->Connect("localhost", "root", "password", "mydb");
連結(jié)的程序代碼比起原來MySQL的程序代碼有老練一些,因為我們正是需要更老練些。在ADODB我們使用對象導(dǎo)向的方法來管理多樣數(shù)據(jù)庫的復(fù)雜性,我們用不同類(class)來控制不同數(shù)據(jù)庫。假如你不熟悉對象導(dǎo)向程序設(shè)計,別擔心!所有的復(fù)雜事情都隱藏在 NewADOConnection() 函數(shù)之后。
為了節(jié)省內(nèi)存,我們只加載與你所連結(jié)數(shù)據(jù)庫相關(guān)的PHP程序代碼,我們通過調(diào)用NewADOConnection(databasedriver)來完成這件事,合法的數(shù)據(jù)庫驅(qū)動程序包含 mysql,mssql,oracle,oci8,postgres,sybase,vfp,access,ibase 以及許多其它的驅(qū)動程序。
接著我們通過調(diào)用 NewADOConnection() 來從連結(jié)類別產(chǎn)生一個新的對象實體,最后我們使用 $db->Connect() 來連結(jié)數(shù)據(jù)庫。
執(zhí)行SQL指令
$result = $db->Execute("SELECT * FROM employees");
if ($result === false) die("failed");
直接傳送SQL指令到服務(wù)器,當成功執(zhí)行之后,Execute()將傳回一個recordset對象,你可以如同上面所列來檢查$result。
一個初學(xué)者容易混淆的議題是,在ADODB有兩種類型的對象,連結(jié)對象以及recordset對象,我們何時用這些對象呢?
連結(jié)對象($db)是負責連結(jié)數(shù)據(jù)庫,格式化你的SQL查詢。而recordset對象($result)則是負責擷取結(jié)果并將響應(yīng)數(shù)據(jù)規(guī)格化成文字或數(shù)組。
唯一我需要增加的事情是,ADODB提供許多有用的函數(shù)來讓INSERT及UPDATE指令更容易些,這點我們在進階的章節(jié)會提到。
擷取資料
while (!$result->EOF) {
?? for ($i=0, $max=$result->FieldCount(); $i ?????? print $result->fields[$i].' ';
?? $result->MoveNext();
?? print "
n";
}
前面取得數(shù)據(jù)的范例很像從檔案讀數(shù)據(jù),在每一行我們首先檢查是否到了檔案的結(jié)尾(EOF),若還沒到結(jié)尾,循環(huán)掃過每列中的字段,然后移到下一行(MoveNext)接著重復(fù)同樣的事情。
$result->fields[]數(shù)組是由PHP數(shù)據(jù)庫延伸系統(tǒng)所產(chǎn)生的,有些數(shù)據(jù)庫延伸系統(tǒng)并不會以字段名稱建立該數(shù)組的索引,要強迫以名稱排序索引該數(shù)組,使用$ADODB_FETCH_MODE的通用變量。
??????? $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
??????? $rs1 = $db->Execute('select * from table');
??????? $ADODB_FETCH_MODE = 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儲存并使用不同的取用模式,當recordset由Execute()產(chǎn)生后再設(shè)定$ADODB_FETCH_MODE。
ADOConnection
連結(jié)到數(shù)據(jù)庫的對象,執(zhí)行SQL指令并且有一組工具函數(shù)來標準格式化SQL指令,比如關(guān)聯(lián)與日期格式等指令。
其它有用的函數(shù)
$recordset->Move($pos)卷動目前的數(shù)據(jù)列,ADODB支持整個數(shù)據(jù)庫往前卷動,有一些數(shù)據(jù)庫并不支持往后的卷動,這倒不會是個問題,因為你能夠用暫存紀錄到快取來仿真往后卷動。
$recordset->RecordCount()傳回SQL指令存取到的紀錄筆數(shù),有些數(shù)據(jù)庫會因為不支持而傳回-1。
$recordset->GetArray()以數(shù)組的方式傳回結(jié)果。
rs2html($recordset)函數(shù)將傳進的recordset轉(zhuǎn)為HTML的表格格式。下例中以粗體字顯示相關(guān)用法:
include('adodb.inc.php');
include('tohtml.inc.php'); /* includes the rs2html function */
$conn = &ADONewConnection('mysql');
$conn->PConnect('localhost','userid','password','database');
$rs = $conn->Execute('select * from table');
rs2html($rs); /* recordset to html table */
還有許多其它有用的函數(shù)列示在文件之中,可從下列網(wǎng)址查得 http://php.weblogs.com/adodb_manual
進階題材
新增及更新
假設(shè)你要新增下列數(shù)據(jù)到數(shù)據(jù)庫中。
ID = 3
TheDate=mktime(0,0,0,8,31,2001) /* 31st August 2001 */
Note= sugar why don't we call it off
當你改用別的數(shù)據(jù)庫,可能就沒辦法新增數(shù)據(jù)。
第一個問題是,每一個數(shù)據(jù)庫各自有不同的內(nèi)定日期格式,MySQL使用 YYYY-MM-DD 格式,而其它數(shù)據(jù)庫則有不同的內(nèi)定格式,ADODB提供DBDate()函數(shù)來轉(zhuǎn)換不同數(shù)據(jù)庫之間的日期內(nèi)定格式。
次一個問題是單引號(don't)的表示法,在MySQL可以直接使用單引號(don't),但在其它數(shù)據(jù)庫如Sybase、Access、 Microsoft SQL Server,則用兩個單引號表示(don''t),qstr()函數(shù)可以解決此問題。
我們?nèi)绾问褂眠@些函數(shù)?就像這樣:
$sql = "INSERT INTO table (id, thedate,note) values ("
?? . $ID . ','
?? . $db->DBDate($TheDate) .','
?? . $db->qstr($Note).")";
$db->Execute($sql);
ADODB還有$connection->Affected_Rows()函數(shù),傳回受最后update或delete指令影響的數(shù)據(jù)列數(shù),及$recordset->Insert_ID()函數(shù),傳回最后因insert指令而自動產(chǎn)生的數(shù)據(jù)列編號,預(yù)先提醒大家,沒有任何數(shù)據(jù)庫有提供這兩個函數(shù)。
MetaTypes
你可以得到關(guān)于字段的更多信息,透過recordset的方法FetchField($fieldoffset)傳回對象的3個屬性:name,type,max_length。
舉例說明:
$recordset = $conn->Execute("select adate from table");
$f0 = $recordset->FetchField(0);
結(jié)果$f0->name的內(nèi)容是'adata',$f0->type將是'date',假如max_length不知道,其內(nèi)容將會是-1。
處理不同數(shù)據(jù)庫的一個問題是,每一個數(shù)據(jù)庫對于相同的數(shù)據(jù)型態(tài)會有不同的稱呼,比如timestamp型態(tài)在某數(shù)據(jù)庫中稱為datetime,而另一個數(shù)據(jù)庫則稱為time,所以ADODB提供MetaType($type,$max_length)函數(shù)來標準化下列的數(shù)據(jù)型態(tài):
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)
在前面的例子中,
$recordset = $conn->Execute("select adate from table");
$f0 = $recordset->FetchField(0);
$type = $recordset->MetaType($f0->type, $f0->max_length);
print $type; /* should print 'D' */
Select指令的Limit及Top支持
ADODB有個$connection->SelectLimit($sql,$nrows,$offset)函數(shù)讓你擷取recordset的部分集合,這是采用Microsoft產(chǎn)品中的SELECT TOP用法,及PostgreSQL與MySQL中的SELECT...LIMIT用法的優(yōu)點,即使原來的數(shù)據(jù)庫并沒有提供此用法,本函數(shù)也仿真提供該使用方式。
快取支援
ADODB允許你在你的檔案系統(tǒng)中暫存recordset的數(shù)據(jù),并且在$connection->CacheExecute($secs2cache,$sql)及 $connection->CacheSelectLimit($secs2cache,$sql,$nrows,$offset)等設(shè)定的時間間隔到達之后,才真正去做數(shù)據(jù)庫的查詢以節(jié)省時間。
PHP4 Session支持
ADODB也支持PHP4 session handler,你可以存放你的session變量在數(shù)據(jù)庫中,相關(guān)功能請參考 http://php.weblogs.com/adodb-sessions
鼓勵商業(yè)使用
假如你計劃寫商用的PHP應(yīng)用軟件來銷售,你也可以使用ADODB,我們依據(jù)GPL來出版ADODB,也就是說你可以合法地在商用應(yīng)用軟件中引用,并保有你程序代碼的所有權(quán)。強烈地鼓勵A(yù)DODB的商業(yè)應(yīng)用,我們自己內(nèi)部也正以這個理由如此使用中。

Hot AI Tools

Undress AI Tool
Undress images for free

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

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

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Avoid N 1 query problems, reduce the number of database queries by loading associated data in advance; 2. Select only the required fields to avoid loading complete entities to save memory and bandwidth; 3. Use cache strategies reasonably, such as Doctrine's secondary cache or Redis cache high-frequency query results; 4. Optimize the entity life cycle and call clear() regularly to free up memory to prevent memory overflow; 5. Ensure that the database index exists and analyze the generated SQL statements to avoid inefficient queries; 6. Disable automatic change tracking in scenarios where changes are not required, and use arrays or lightweight modes to improve performance. Correct use of ORM requires combining SQL monitoring, caching, batch processing and appropriate optimization to ensure application performance while maintaining development efficiency.

The settings.json file is located in the user-level or workspace-level path and is used to customize VSCode settings. 1. User-level path: Windows is C:\Users\\AppData\Roaming\Code\User\settings.json, macOS is /Users//Library/ApplicationSupport/Code/User/settings.json, Linux is /home//.config/Code/User/settings.json; 2. Workspace-level path: .vscode/settings in the project root directory

PHP's garbage collection mechanism is based on reference counting, but circular references need to be processed by a periodic circular garbage collector; 1. Reference count releases memory immediately when there is no reference to the variable; 2. Reference reference causes memory to be unable to be automatically released, and it depends on GC to detect and clean it; 3. GC is triggered when the "possible root" zval reaches the threshold or manually calls gc_collect_cycles(); 4. Long-term running PHP applications should monitor gc_status() and call gc_collect_cycles() in time to avoid memory leakage; 5. Best practices include avoiding circular references, using gc_disable() to optimize performance key areas, and dereference objects through the ORM's clear() method.

ReadonlypropertiesinPHP8.2canonlybeassignedonceintheconstructororatdeclarationandcannotbemodifiedafterward,enforcingimmutabilityatthelanguagelevel.2.Toachievedeepimmutability,wrapmutabletypeslikearraysinArrayObjectorusecustomimmutablecollectionssucha

Bref enables PHP developers to build scalable, cost-effective applications without managing servers. 1.Bref brings PHP to AWSLambda by providing an optimized PHP runtime layer, supports PHP8.3 and other versions, and seamlessly integrates with frameworks such as Laravel and Symfony; 2. The deployment steps include: installing Bref using Composer, configuring serverless.yml to define functions and events, such as HTTP endpoints and Artisan commands; 3. Execute serverlessdeploy command to complete the deployment, automatically configure APIGateway and generate access URLs; 4. For Lambda restrictions, Bref provides solutions.

UseaRESTAPItobridgePHPandMLmodelsbyrunningthemodelinPythonviaFlaskorFastAPIandcallingitfromPHPusingcURLorGuzzle.2.RunPythonscriptsdirectlyfromPHPusingexec()orshell_exec()forsimple,low-trafficusecases,thoughthisapproachhassecurityandperformancelimitat

First, use JavaScript to obtain the user system preferences and locally stored theme settings, and initialize the page theme; 1. The HTML structure contains a button to trigger topic switching; 2. CSS uses: root to define bright theme variables, .dark-mode class defines dark theme variables, and applies these variables through var(); 3. JavaScript detects prefers-color-scheme and reads localStorage to determine the initial theme; 4. Switch the dark-mode class on the html element when clicking the button, and saves the current state to localStorage; 5. All color changes are accompanied by 0.3 seconds transition animation to enhance the user

Create a seeder file: Use phpartisanmake:seederUserSeeder to generate the seeder class, and insert data through the model factory or database query in the run method; 2. Call other seeder in DatabaseSeeder: register UserSeeder, PostSeeder, etc. in order through $this->call() to ensure the dependency is correct; 3. Run seeder: execute phpartisandb:seed to run all registered seeders, or use phpartisanmigrate:fresh--seed to reset and refill the data; 4
