Ten instances of AdoDB [reproduced]
Ten instances of AdoDB
Transfer from http://www.ilovezhuzhu.net/discuz !/viewthread.php?tid=629&sid=2fe8hqj3 I want to learn PEAR, but the few posts seen on the Internet are quite high, so I have changed this. AdoDB's advantages have these few (online, not what I said): 1, speed is doubled fast than PEAR; 2, supported database types are much more than PEAR, can even support Access; 3, no need to install, no server Support (for novices, this is very important) I don't know what adoDB is or want to download Adodb's friends can go to this link: http://www.phpe.net/class/106.shtml addition, if Which brother translated the full text of Readme or know where there is a translation, please return to a post, thank you.
Tutorial Example 1: SELECT Statement Task: Connect a ACCESS database called Northwind to display the first two fields of each record. In this instance, we create an AdoCONNECTION object and use it to connect to a database. This connection uses a PConnect method, which is a persistent connection. When we want to query the database, we can call this connection with the execute () function. It returns an AdorecordSet object which is actually a cursor that Holds The Current Row in The Array FIELDS [] We use MoveNext () to turn from a record to the next record. NB: There is a very useful function SelectLimit is not used in this example, it can control the number of recorded records (such as only the top ten records, can Used as paging display). PHP code: ----------------------------------------------------------- --------------------------------------- incrude ('adodb.inc.php " ); # A = "; # Newly built a connection $ conn-> PConnect ('northwind'); # Connect to a MS-Access database data source called Northwind $ RecordSet = & $ Conn-> EXECUTE ('SELECT * from products'): # From the Products data table, all data IF (! $ recordset) Print $ conn-> errormsg (); // If the data search occurs error display error message Else While ! $ recordset-> EOF) {Print $ RecordSet-> Fields [0]. ''. $ recordset-> fields [1]. '
'; $ recordset-> MoveNext (); // point to the next record } // list display data $ recordset-> close (); // Optional $ conn-> close (); // Optional?> -------------------------------------------------------------------------------------------------------------------- ---------------- -------------------------------------------- $ Recordset in $ Returning the current array in the recordset-> fields, digital indexing of the field (starting from 0). We move to the next record with the MoveNext () function. When the database searches the end, EOF Property is set to true. If Execute () occurs Error, Recordset returns a FLASE. $ RecordSet-> Fields [] array is generated in PHP database extensions. Some database extensions can only be indexed by digital index but cannot be used in the field name. If you insist on using the field name index, you should use the setFetchMode function. No matter which format index, the Recordset can be created by Execute () or selectLimit ().
PHP code: ----------------------------------------------- -------------------------------- $ db-> setfetchmode (adoDb_fetch_num); $ r1 = $ db-> execute ('select * from table'); // uses digital index $ db-> setfetchmode; $ r2 = $ db-> execute ('select * from table'); // uses field name index Print_R ($ RS1) -> Fields; # shows array ([0] => 'V0', [1] => 'V1') Print_R ($ r2-> fields); # shows array (['col1'] => 'V0' ['col2'] => 'V1') -------------------------------------- ------------------------------------------ If you want to get the record number, you can Use $ RecordSet-> RecordCount (). Returns -1 if there is no current record.
Example 2: Advanced SELECT WITH FIELD OBJECTS Search Table, display the first two fields. If the second field is time or date format, it will be changed to the US standard time format display. PHP code: -------- -------------------------------------------------- ---------------------- include ('adoDb.inc.php'); // Load AdoDB $ conn = & adonewconnection ('access ") ; // Newly create a connection $ conn-> pConnect ('northwind'); // Connect the MS-Access database named Northwind $ RecordSet = & $ conn-> execute ('select customerid, orderdate from orderrs'); ///// Search for Customerid and ORDERDATE from ORDERS Table IF (! $ Recordset) Print $ conn-> errormsg (); // If the database search error, display error message Else While (! $ Recordset-> EOF) {$ fld = $ RecordSet-> Fetchfield (1); // assign the second field to $ fld $ type = $ recordset-> metatype ($ fld-> type); // Take a field value format IF ($ TYPE == ' D '|| $ TYPE ==' T ') Print $ RecordSet-> Fields [0].' '. $ Recordset-> Userdate ($ recordset-> fields [1],' m / d / y ').'
'; // If the field format is a date or time shape, it outputs Else Print $ RecordSet-> Fields [0].' '. $ RecordSet-> Fields [1].'
'; // Otherwise output $ RecordSet-> MoveNext (); // point to the next record} $ recordset-> close (); // Optional $ conn-> close (); // Optional?> - -------------------------------------------------- ----- ------------------------ In this example, we check the format of the second field with the fetchfield () function. It returns one containing three Object Name: Field Name: Field Name Type: Fields in its database Max_length: Field maximum length, some databases do not return this value, such as MySQL, this case Max_length value is equal to -1. We use metatype () Transform the field database format into a standard field format C: Character field, it should be displayed under tag. X: Text field, store a relatively large text, generally acting on
We use user-defined date format userdate () functions, userdate () is used to convert the PHP SQL date string format to user-defined format, and another usage of metatype () is to confirm data validity before insertion and replacement. ......................................................... .. -------------------------------------------------- ---------------------- include ('adoDb.inc.php'); // Load AdoDB $ conn = & adonnection ('access "); // Create a new connection $ conn-> pConnect ('northwind'); // Connect to Access Database Northwind $ Shipto = $ Conn-> QSTR ("John's Old Shoppe"); $ SQL = "Insert INTO Orders (Customerid, Employeeid , OrderDate, ShipName) "; $ SQL. =" Values ('AnaTr', 2, ". $ Conn-> dbdate (time ()).", $ Shipto "; if ($ conn-> execute ($ SQL ) === false) {print 'error inserting:'. $ conn-> erroormsg (). '
';} // If inserted unsuccessful output error message?> ---------- -------------------------------------------------- -------------------- In this example, we see AdoDB to easily handle some advanced database operations. UNIX timestamp (a long integer) is dbdate () Convert to the correct Access format, and the right escape character is buy for quoting the john's old shoppe, Which is john ''s old shoppe and not php's default john's ol D shoppe with qstr (). Observe the error handling of the execution statement. If the execute () has an error, the ERRORMSG () function returns the last error message. Note: php_track_errors might Have to be enabled for error messages to be saved. instance 4: DEBUGGING Include ('adoDb.inc.php'); // Load AdoDB $ conn = & adonnection ('access'); // Newly built a connection $ conn-> pConnect ('northwind'); // Connect to Access Database Northwind $ shipto = $ conn-> qstr ("John's Old Shoppe"); $ SQL = "Insert Into Orders (Customerid, Employeeid, ORDERDATE, ShipName"; $ SQL. = "Values ('AnaTr', 2," . $ conn->
Formatdate (Time ()). ", $ Shipto"; $ conn-> debug = true; if ($ conn-> execute ($ SQL) === false) Print 'Error Inserting';> In these examples In the case, we set the debug = true. It will display all SQL messages before execution, and it will also display all error tips. In this example, we no longer need to call errormsg (). To display RecordSet, you can refer to RS2HTML () instance. You can also refer to some of the contents of Custom Error Handlers.
Example 5: MySQL and MENUS Connect to the MySQL Database Agora, and generate a
Select * from table query where ... ", make a copy of the $ rs-> fields, modify the fields, and the generate the sql to update or insert intert insert inteomatic. Let's take a look at this two functions in this how worksheet is performed: (ID, FirstName, LastName, Created) Before these functions can be called, you need to initialize the recordset by performing a select on the table Idea and code by Jonathan Younger jyounger # unilab.com.. PHP code: ---------------------------------------------- ---------------------------------- # ============= ================================================================================================================================================================================ =================================================================================================================================================================================================================================================================================★ Include ('Tohtml.inc.php'); // Weird, this seems to have all, which friend knows the reason, please give an explanation # ================ ========== # this code tests an insert $ sql = "select * from adoxyz where id = -1"; # 查 一 空 记 $ conn = & adonewconnection ("mysql"); # create a connection $ conn-> debug = 1; $ conn-> pconnect ("localhost", "admin", "" ""); # connect to mysql, testdb $ r = $ conn-> execute ($ sql); # Get an empty record $ Record = array (); #7704 准 准 插 # # 设置
$ Record [ "created"] = time (); # Pass the empty recordset and the array containing the data to insert # into the GetInsertSQL function The function will process the data and return # a fully formatted insert sql statement # before insertion. Formatting variable $ INSERTSQL = $ conn-> getInsertsql ($ RS, $ Record); $ conn-> execute ($ INSERTSQL); # in the database into data # ============= ============ # The following program demonstrates the data, which is approximately the same as the last program. SQL = "Select * from adoxyz where id = 1"; # select a record to update $ = r = $ conn-> Execute ($ sql); # Execute the query and get the existing record to update $ record = array (); # Initialize an array to hold the record data to update # Set the values for the fields in the record $ record [ "firstname"] = "Caroline"; $ record [ "lastname"] = "Smith"; # Update Caroline's lastname from Miranda to Smith # Pass the single record recordset and the array containing the data to update # into the GetUpdateSQL Function. The Function Will Process The Data And Return # a full formatted Update SQL Statement with the Correct Where Clause . # I recordset is returned $ updatesql = $ conn-> getUpdatesql ($ RS, $ Record); $ conn-> execute ($ updateSQL); # Update The Record in The Database $ conn-> CLOSE ();?> -------------------------------------------- ----------------------------------- Example 8 Implementing Scrolling With Next and Previous The presentation is a small Paging browsing program. PHP code: ------------------------------------------------------------------------------------------------------------------------------------ -------------------------------------- Include_once ('../ adodb.inc.php' ); include_once ('../ adoDB-pAger.inc.php'); session_start ();
$ db = newadoconnection ('mysql'); $ db-> connect ',' ',' xphplens'); $ sql = "select * from adoxyz"; $ pacer = new adoDB_pager ($ db $ SQL); $ pager-> render ($ rows_per_page = 5); --------------------------------- ------------------------------------------------ run the above The results of the program are as follows: | << >>> | ID FIRST NAME Last Name Date Created 36 Alan Turing Sat 06, Oct 2001 37 Serena Williams Sat 06, Oct 2001 38 Yat Sun SUN SAT 06, OCT 2001 39 WAI HUN SEE SAT 06, OCT 2001 40 Steven Oey Sat 06, Oct 2001 Page 8/10 Call the Render ($ ROWS) method You can page the display data. If you don't give the render () input value, the adoDb_pager default value is 10 records per page. You You can select the arbitrary field in SQL and define the name: $ sql = 'select ID "id", firstname as "first name", Lastname as "last name", created as "deated" from adoxyz'; Code You can find in AdoDB / Tests / TestPaging.php, AdoDB_Pager objects in AdoDB / AdoDB-Pager.inc.php. You can add images and change your color to AdoDB_Pager, you can set $ pager-> htmlspecialchars = false to display HTML code. Some of the code used here atten i iván oliva and cornel G. EXAMPLE 9: Exporting In CSV or Tab-Delimited Format WE PROVIDE SOMMA-SEPARATED-VALUE (CSV) and Tab-Delimited Formats: PHP Code: ---------------------------------------------------------------------------------------------------- -------------------------------------------------- ---- Include_once ('/ path / to / adoDb / toexport.inc.php'); include_once ('/ path / to / adoDb / adodb.inc.inc.php'); $ dB = & newadoconnection ('mysql'); $ DB-> Connect ($ server, $ userid, $ password, $ database); $ = $ db-> execute ('SELECT FNAME AS "First Name", Surname As "Surname" from Table'); Print PRE> "; Print RS2CSV ($ RS); # Return A String, CSV Formatprint '