what is "PDO?" PDO is a significant feature of PHP5 's new addition, because before PHP5 php4/php3 are a bunch of database extensions to connect and process with each database, what Php_mysql.dll, Php_pgsql.dll, Php_mssql.dll, Php_sqlite.dll, and so on to connect MySQL, PostgreSQL , MSSQLServer, SQLite, the same, we must rely on the ADODB, PEAR:B, phplib:b and other database abstract class to help us, extremely cumbersome and inefficient, after all, the efficiency of PHP code how can we directly use C + +write the extension slope high pinch? So, the appearance of PDO is inevitable, we have to calm learning attitude to accept the use, perhaps you will find that you can reduce a lot of kung fu Oh. "Install PDO" I was on the WindowsXPSP2, so the whole process was done on Windows, as for Linux/FreeBSD and other platforms, please find your own data set up installation. Mine is PHP5.1.4, already has an extension of php_pdo.dll, but it needs to be set up a little bit to be used. Open C:\windows\php.ini, that is my PHP configuration file, find the following line: Extension_dir This is our extension exists directory, my PHP5 extension is in: C:\php5\ext, then I will change this line to: Extension_ Dir="C:/php5/ext"the above in the PHP environment has been modified, there is no need to change. Then go to Wq below:;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;D ynamicextensions;;;;;;;;;;;;;;;;;;;;;;;;; There is a bunch of similar; extension=Php_mbstring.dll, here is the PHP extension load configuration, we add the last side of our PDO extension: extension=php_pdo.dllextension=php_pdo_mysql.dllextension=php_pdo_pgsql.dllextension=php_pdo_sqlite.dllextension=php_pdo_mssql.dllextension=php_pdo_odbc.dllextension=php_pdo_firebird.dll;extension=Php_pdo_oci8.dll A variety of PDO driver, can give plus, but the back of the Php_pdo_oci8.dll, because I did not install Oralce database, so without this, use semicolons to comment out it. Then restart our web server, IIS/Apache, My is IIS, Hey, watch despise me, on windows, simple. After rebooting, write a phpinfo.php file in our Web server's documentation directory, plus these:?phpinfo ();?> Then open our lovely browser: IE/firefox, mine is FireFox2.0, just downloaded, very cool, not afraid of rogue software, haha. Enter in the browser: http://localhost/phpinfo.php, if your page path is inconsistent, please enter it yourself. The output of the content, if you can see smoothly: Pdopdosupportenabledpdodriversmysql,pgsql,sqlite,mssql,odbc,firebird behind a variety of driver instructions: pdo_ Firebird,pdo_mssql,pdo_mysql,pdo_odbc,pdo_pgsql,pdo_sqlite Well, congratulations on your installation, otherwise please check the above steps carefully. "Sledgehammer small Try" I use MySQL4.0.26, but I personally recommend that you use MySQL4.1. x or MySQL5.0. x, because those editions have lots of interesting things to learn. Our PDO need to connect is my MySQL4.0, if you do not install MySQL, please install it yourself. We built MySQL and added table foo to the test library, including four fields such as Id,name,gender,time. We started constructing the first PDO application, creating a pdo.php file under the Web document directory:?PHP $dsn="mysql:host=localhost;dbname=test"; $db=newpdo ($DSN,'Root',"'); $count= $db->exec ("insertintofoosetname= ' Heiyeluren ', gender= ' man ', Time=now ()"); Echo$count; $db=NULL;?> Don't understand what that means, let's talk about it slowly. This line: $dsn="mysql:host=localhost;dbname=test"is to construct our DSN (data source) and look at the information included: the database type is MySQL, the host address is localhost, the database name is test, just a few messages. Data sources in different databases are constructed differently. $db=newpdo ($DSN,'Root',"'); Initializes a PDO object, constructor parameters the first one is our data source, the second is the user who connects to the database server, and the third parameter is the password. We cannot guarantee that the connection is successful, we will talk about the exception later, and here we would consider it to be a successful connection. $count= $db->exec ("insertintofoosetname= ' Heiyeluren ', gender= ' man ', Time=now ()"); echo$count; Call our successful PDO object to execute a query that is an operation that inserts a record, and uses the Pdo::exec () method to return a result that affects the record, so we output this result. Finally, you need to end the object resource: $db=NULLdefault this is not a long connection, if you need a long database connection, you need to add one last parameter: Array (pdo::attr_persistent=>true) into this: $db=newpdo ($DSN,'Root',"', Array (pdo::attr_persistent=>true)); One operation is so simple, perhaps not much different from the previous, and ADODB is somewhat similar. "Continue to understand" if we want to extract data, then we should use the data acquisition function. (The $db used below are all connected objects above)?PHPforeach($db->query ("Select*fromfoo") {print_r ($row);}?> We can also use this access method:?PHP $rs= $db->query ("Select*fromfoo"); while($row = $rs->fetch ()) {Print_r ($row);}?> If you want to get the data in the array at once, you can do this:?Php$rs= $db->query ("Select*fromfoo"); $result _arr= $rs->fetchall ();p rint_r ($result _arr);?>array ([0]=>array ([id]=>1[0]=>1[Name]=>heiyeluren [1]=>heiyeluren [Gender]=> male [2]=> Male [TIME]=>2006-Ten-2823: -: at[3]=>2006-Ten-2823: -: atwe look at the records inside, the digital index and the associated index, the waste of resources, we just need to correlate the index:?php$db->setattribute (pdo::attr_case,pdo::case_upper); $rs= $db->query ("Select*fromfoo"); $rs->setfetchmode (PDO::FETCH_ASSOC); $result _arr= $rs->fetchall ();p rint_r ($result _arr);?> Look at the code above, the SetAttribute () method is to set some properties, the main properties are: Pdo::attr_case, Pdo::attr_errmode and so on, we need to set the pdo::attr_case here, is when we use the associated index to get the data set, whether the associated index is uppercase or lowercase, there are several choices: Pdo::case_lower--Force column names to be lowercase pdo::case_natural--column names are pdo::case_upper in the original way--Force column name to uppercase we use the Setfetchmode method to set the type of the return value that gets the result set, and the same type: Pdo::fetch_assoc--associative array form pdo::fetch_num--Digital Index Array form Pdo::fetch_both--both arrays are of the form, which is the default Pdo::fetch_obj--in the form of an object, similar to the previous mysql_fetch_object () of course, generally we are using PDO::FETCH_ASSOC, specifically what to use, follow your own needs, other get type reference manuals. In addition to the above-mentioned way of obtaining data, there is this:?Php$rs= $db->prepare ("Select*fromfoo"); $rs->execute (); while($row = $rs->fetch ()) {Print_r ($row);}?> > Actually, it's almost there. If you want to get a result from a field in the specified record, you can use Pdostatement::fetchcolumn ():?Php$rs= $db->query ("SelectCount (*) Fromfoo"); $col= $rs->fetchcolumn (); echo$col;?> generally use Fetchcolumn () for Count statistics or some records that require only a single field to operate well. A simple summary of the above operation: The query operation is mainly Pdo::query (), Pdo::exec (), PDO::p repare (). Pdo::query () is primarily used for operations that have logged results returned, particularly the select operation, where Pdo::exec () is primarily for operations that do not have a result set, such as INSERT, UPDATE, delete, and so on, which returns the number of columns affected by the current operation. PDO::p Repare () is primarily a preprocessing operation that needs to be $rs->execute () to perform preprocessing inside the SQL statement, this method can bind parameters, the function is relatively strong, not this article can be simple to understand, you can refer to manuals and other documents. The main operations for getting result sets are: Pdostatement::fetchcolumn (), Pdostatement::fetch (), Pdostatement::fetchall (). Pdostatement::fetchcolumn () is a field that gets the result that specifies the first record, and the default is the first field. Pdostatement::fetch () is used to get a record, Pdostatement::fetchall () is to get all the recordset into one, and get the result can be pdostatement by: Setfetchmode to set the type that requires the result collection. There are also two peripheral operations, one of which is Pdo::lastinsertid () and Pdostatement::rowcount (). Pdo::lastinsertid () is the last insert operation returned, and the primary key column type is the final self-increment ID. Pdostatement::rowcount () is primarily used for pdo::query () and PDO::p Repare () for the result set affected by the delete, INSERT, update operation, for Pdo::exec () Method and select operation are not valid. "Error Handling" What if an error is encountered in the program? Here we describe the PDO class for error messages and exception handling. 1The object-oriented approach is to take a look at the processing of connection errors and so on, using an object-oriented approach:?PHPTry{$db=newpdo ('mysql:host=localhost;dbname=test', $user, $pass); $db=NULL;}Catch(pdoexception$e) {print"Error:". $e->getmessage ()."
"; Die ();}?> Here we use our PHP5 object-oriented exception handling feature, and initialize call Pdoexception to initialize an exception class if there is an exception. PDOEXCEPTION attribute structure of the exception class:?phpclasspdoexceptionextendsexception{ Public$errorInfo =NULL;//error message, you can call Pdo::errorinfo () or Pdostatement::errorinfo () to access protected$message;//exception information, you can try Exception::getmessage () to access protected$code;//SQL Status error code, you can use Exception::getcode () to access}?> This exception handling class is an integrated PHP5 built-in exception handling class, so let's take a quick look at the PHP5 built-in exception handling class structure:?phpclassexception{//Properties protected$message ='unknownexception';//Exception Information protected$code =0;//user-defined exception codes protected$file;//the file name of the exception that occurred protected$line;//the line number of the code where the exception occurred//MethodFinalfunctiongetmessage ();//Return exception InformationFinalfunctiongetcode ();//return Exception CodeFinalfunctiongetfile ();//returns the file name of the exception that occurredFinalfunctiongetline ();//returns the line number of the code where the exception occurredFinalfunctiongettrace ();//backtrace () arrayFinalfunctiongettraceasstring ();//Gettrace () information that has been rasterized into a string}?it is appropriate to call GetFile () and Getline () in the code to make the error location easier to debug. 2using a process-oriented approach, look at the code first:?$db=newpdo ('mysql:host=localhost;dbname=test', $user, $pass); $rs= $db->query ("Selectaa,bb,ccfromfoo");if($db->errorcode ()! ='00000') {Print_r ($db->errorinfo ()); Exit;} $arr= $rs->fetchall ();p rint_r ($arr); $db=NULL;?The >pdo and Pdostatement objects have the ErrorCode () and ErrorInfo () methods, and if there are no errors, ErrorCode () returns:00000, or you will return some error codes. An array of errorinfo () returns, including PHP-defined error codes and MySQL error codes and error messages, with the following array structure: Array ([0]=>42s22 [1]=>1054[2]=>unknowncolumn'AAA'inch'FieldList'after each query execution, the results of ErrorCode () are up to date, so we can easily control the display of error messages. "Simple Summary" from the above use, the PDO function is really powerful, there are some content I did not mention, such as binding parameters, preprocessing, stored procedures, transaction processing and so on. There are different data extension DSN constructs, Oracle database own a lot of special things, need to go deep to learn to understand, this article simply describes some of the introductory knowledge, is a simple understanding of PDO. (The operation is simple: Open the C:\windows\php.ini file to find a heap similar to the one below; extension=Php_mbstring.dll, here is the PHP extension load configuration, we add the last side of our PDO extension: extension=php_pdo.dllextension=php_pdo_mysql.dllextension=php_pdo_pgsql.dllextension=php_pdo_sqlite.dllextension=php_pdo_mssql.dllextension=php_pdo_odbc.dllextension=php_pdo_firebird.dll;extension=Php_pdo_oci8.dll Last restart of IIS/apache.ok.)
Note: To configure the database with PDO, remove the semicolon from the front of the php.ini file and restart it.
Configuration and description of PDO in PHP