Simple use of PDO in PHP5

Source: Internet
Author: User
Tags ibm db2 phpinfo

Author: heiyeluren <Http://blog.csdn.net/heiyeshuwu>
Time: 2006-10-29
Keywords: PHP PHP5 PDO database abstract class

PDO (PHP Data Object) is a new feature of PHP 5. When PHP 6 is ready, PHP 6 uses PDO to process databases by default, by default, all the database extensions are moved to PECL, so we don't have php_mysql.dll and so on. So what should we do? We have to keep up with the times, so I tried PDO. (This article is only an entry level. You can skip it)

[What is PDO]

PDO is a major new feature of PHP 5, because php4/php3 before PHP 5 was a bunch of database extensions to connect to and process various databases, php_mysql.dll, php_pgsql.dll, php_mssql.dll, php_sqlite.dll, and other extensions to connect to MySQL, PostgreSQL, ms SQL Server, and SQLite. Similarly, we must use ADOdb, PEAR: DB, PHPlib :: database abstract classes such as DB are very cumbersome and inefficient to help us. After all, how can we directly use C/C ++ to write php code with a high scaling slope? Therefore, the emergence of PDO is inevitable. you should accept it with a calm learning attitude. Maybe you will find it can reduce your efforts.

[Install PDO]

I am on Windows XP SP2, so the whole process is performed on Windows. For Linux/FreeBSD and other platforms, please find the information to set and install.
My PHP version is 5.1.4 and I already have the php_pdo.dll extension, but I need to set it up a little before it can be used.

Open c: \ windows \ php. ini, which is my PHP configuration file. Find the following line:
Extension_dir
This is the directory of our extension. My PHP 5 extension is in: C: \ php5 \ ext, so I will change this line:

Extension_dir = "C:/php5/ext"

Then find the following link under php. ini:

;;;;;;;;;;;;;;;;;;;;;;
; Dynamic Extensions;
;;;;;;;;;;;;;;;;;;;;;;

Below are a bunch of things similar to extension = php_mbstring.dll. Here is the PHP extension loading configuration. We will add our PDO extension at the end:

Extension = php_pdo.dll
Extension = php_pdo_mysql.dll
Extension = php_pdo_pgsql.dll
Extension = php_pdo_sqlite.dll
Extension = php_pdo_mssql.dll
Extension = php_pdo_odbc.dll
Extension = php_pdo_firebird.dll
; Extension = php_pdo_oci8.dll

All kinds of PDO drivers can be added, but the php_pdo_oci8.dll in the future will be commented out using semicolons because I have not installed the Oralce database. Then restart our Web server, IIS/Apache, and I use IIS. Hey hey, the table despise me. It's easy on Windows.
After the restart, write a phpinfo. php file under the document directory of our Web server, and add the following:

<?
Phpinfo ();
?>

Then open our lovely Browser: IE/FireFox. I use FireFox 2.0. I just downloaded it. It's so nice. I'm not afraid of rogue software. Haha.
Enter:Http: // localhost/phpinfo. phpIf the path of your page is inconsistent, enter the path on your own.
In the output content, if you can see smoothly:

PDO
PDO support enabled
PDO drivers mysql, pgsql, sqlite, mssql, odbc, firebird

The following describes various drivers,
PDO_Firebird, pdo_mssql, pdo_mysql, PDO_ODBC, pdo_pgsql, pdo_sqlite

Congratulations, you have successfully installed it. Otherwise, Please carefully check the above steps.

[Knife test]

I use MySQL 4.0.26, but I personally recommend that you use MySQL 4.1.x or MySQL 5.0.x because there are many interesting things worth learning. Here, we need to connect to my MySQL 4.0. If you have not installed MySQL, install it on your own. We have created MySQL and added table foo in the test Library, including four fields: id, name, gender, and time.

We started to construct the first PDO application and create a pdo. php file under the Web document directory:

<? Php
$ Dsn = "mysql: host = localhost; dbname = test ";
$ Db = new PDO ($ dsn, 'root ','');
$ Count = $ db-> exec ("insert into foo SET name = 'heiyeluren', gender = 'male', time = NOW ()");
Echo $ count;
$ Db = null;
?>

Don't understand what it means, let's talk about it slowly. This line:
$ Dsn = "mysql: host = localhost; dbname = test ";
It is to construct our DSN (Data Source). Let's see the following information: the database type is mysql, the host address is localhost, and the database name is test. The data source construction methods for different databases are different.

$ Db = new PDO ($ dsn, 'root ','');
Initialize a PDO object. The first parameter of the constructor is our data source, the second parameter 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 exceptions later. Here we will consider it successful.

$ Count = $ db-> exec ("insert into foo SET name = 'heiyeluren', gender = 'male', time = NOW ()");
Echo $ count;
Call the successfully connected PDO object to execute a query. This query is an operation to insert a record. Using the PDO: exec () method, a result that affects the record is returned, so we output this result. Finally, you need to end the object Resource:
$ Db = null;

By default, this is not a persistent connection. If you need a persistent connection to the database, you must add the following parameter: array (PDO: ATTR_PERSISTENT => true:
$ Db = new PDO ($ dsn, 'root', '', array (PDO: ATTR_PERSISTENT => true ));

One operation is so simple. It may not be much different from the previous one. It is somewhat similar to ADOdb.

[Continue]

If we want to extract data, we should use the data acquisition function. (The $ db used below is all the connected objects above)

<? Php
Foreach ($ db-> query ("SELECT * FROM foo ")){
Print_r ($ row );
}
?>

We can also use this method:

<? Php
$ Rs = $ db-> query ("SELECT * FROM foo ");
While ($ row = $ rs-> fetch ()){
Print_r ($ row );
}
?>

If you want to get all the data to the array at one time, you can do this:

<? Php
$ Rs = $ db-> query ("SELECT * FROM foo ");
$ Result_arr = $ rs-> fetchAll ();
Print_r ($ result_arr );
?>

Output:

Array
(
[0] => Array
(
[Id] => 1
[0] => 1
[Name] => heiyeluren
[1] => heiyeluren
[Gender] => male
[2] => male
[Time] => 23:14:23
[3] => 23:14:23
)
}

We can see that the record, the number index and the associated index both exist, which is a waste of resources. We only need to associate the index:

<? Php
$ Db-> setAttribute (PDO: ATTR_CASE, PDO: CASE_UPPER );
$ Rs = $ db-> query ("SELECT * FROM foo ");
$ Rs-> setFetchMode (PDO: FETCH_ASSOC );
$ Result_arr = $ rs-> fetchAll ();
Print_r ($ result_arr );
?>

According to the code above, the setAttribute () method is to set some attributes. The main attributes include PDO: ATTR_CASE, PDO: ATTR_ERRMODE, etc. here we need to set PDO: ATTR_CASE, when we use the associated index to retrieve a dataset, the associated index is in upper or lower case. There are several options:
PDO: CASE_LOWER -- force column name to be lowercase
PDO: CASE_NATURAL -- column names follow the original method
PDO: CASE_UPPER -- force column name to uppercase

We use the setFetchMode method to set the type of the return value for the result set. The same types include:
PDO: FETCH_ASSOC -- join array form
PDO: FETCH_NUM -- numeric index array format
PDO: FETCH_BOTH -- both arrays are available, which is the default
PDO: FETCH_OBJ -- according to the object form, similar to the previous mysql_fetch_object ()

Of course, we generally use PDO: FETCH_ASSOC. For more information about the usage, see the reference manual for other obtaining types.

In addition to the above method of getting data, there are also:

<? Php
$ Rs = $ db-> prepare ("SELECT * FROM foo ");
$ Rs-> execute ();
While ($ row = $ rs-> fetch ()){
Print_r ($ row );
}
?>

Actually, it's almost the same. If you want to obtain the results of a field in a specified record, you can use PDOStatement: fetchColumn ():

<? Php
$ Rs = $ db-> query ("select count (*) FROM foo ");
$ Col = $ rs-> fetchColumn ();
Echo $ col;
?>

FetchColumn () is generally used for count statistics or some records that only need a single field are well-performed.

Briefly summarize the above operations:

Query operations are mainly PDO: query (), PDO: exec (), PDO: prepare (). PDO: query () is mainly used for operations that return record results, especially SELECT operations. PDO: exec () is mainly used for operations that return no result set, for example, INSERT, UPDATE, DELETE, and other operations. The result returned by this operation is the number of columns affected by the current operation. PDO: prepare () is mainly used for preprocessing. You need to use $ rs-> execute () to execute the SQL statements in the preprocessing. This method can bind parameters and has powerful functions, this document is not a simple description. You can refer to the Manual and other documents.

To obtain a result set, perform the following operations: PDOStatement: fetchColumn (), PDOStatement: fetch (), and PDOStatement: fetchALL (). PDOStatement: fetchColumn () is a field of the first record specified in the result. The default value is the first field. PDOStatement: fetch () is used to obtain a record. PDOStatement: fetchAll () is used to obtain all the record sets to one. The obtained results can be obtained through PDOStatement :: setFetchMode to set the type of the desired result set.

There are also two peripheral operations: PDO: lastInsertId () and PDOStatement: rowCount (). PDO: lastInsertId () is the last insert operation, and the primary key column type is the last auto-increment ID of auto-increment. PDOStatement: rowCount () is the result set affected by the DELETE, INSERT, and UPDATE operations on PDO: query () and PDO: prepare :: the exec () method and SELECT operation are invalid.

[Error handling]

What if an error occurs in the program? Here we describe the error information and Exception Handling of the PDO class.

1. object-oriented approach

First, let's take a look at the handling of connection errors, and use the object-oriented method to handle them:

<? Php
Try {
$ Db = new PDO ('mysql: host = localhost; dbname = test', $ user, $ pass );
$ Db = null;
} Catch (PDOException $ e ){
Print "Error:". $ e-> getMessage (). "<br/> ";
Die ();
}
?>

Here we use the object-oriented Exception Handling feature of PHP 5. If there is an exception in it, we will initialize and call PDOException to initialize an exception class.
The property structure of the PDOException class:

<? Php
Class PDOException extends Exception
{
Public $ errorInfo = null; // error message, which can be accessed by calling PDO: errorInfo () or PDOStatement: errorInfo ()
Protected $ message; // Exception information. You can try Exception: getMessage () to access
Protected $ code; // SQL status error code, which can be accessed using Exception: getCode ()
}
?>

This exception handling class is integrated with the PHP 5 built-in exception handling class. Let's take a look at the PHP 5 built-in exception handling class structure:

<? Php
Class Exception
{
// Attributes
Protected $ message = 'unknown exception'; // exception information
Protected $ code = 0; // custom Exception code
Protected $ file; // file name with an exception
Protected $ line; // The code line number with an exception

// Method
Final function getMessage (); // returns exception information
Final function getCode (); // returns the Exception Code
Final function getFile (); // returns the file name with an exception
Final function getLine (); // return the code line number in which an exception occurs.
Final function getTrace (); // backtrace () array
Final function getTraceAsString (); // getTrace () information formatted as a string
}
?>

Correspondingly, you can call getFile () and getLine () in the code to locate the error, making debugging easier.

2. process-oriented methods
First look at the Code:

<?
$ Db = new PDO ('mysql: host = localhost; dbname = test', $ user, $ pass );
$ Rs = $ db-> query ("SELECT aa, bb, cc FROM foo ");
If ($ db-> errorCode ()! = '000000 '){
Print_r ($ db-> errorInfo ());
Exit;
}
$ Arr = $ rs-> fetchAll ();
Print_r ($ arr );
$ Db = null;
?>

The PDO and PDOStatement objects have the errorCode () and errorInfo () methods. If there are no errors, errorCode () returns: 00000. Otherwise, some error codes are returned. An array returned by errorInfo (), including the PHP-defined error code and MySQL error code and error information. The array structure is as follows:

Array
(
[0] => 42S22
[1] => 1054.
[2] => Unknown column 'aaa' in 'field list'
)

After each query, the results of errorCode () are the latest, so we can easily control the display of error information.

[Summary]

From the above usage, we can see that the PDO function is really powerful, and there are some other features that I have not mentioned, such as binding parameters, preprocessing, stored procedures, transaction processing, and so on. In addition, there are also different data expansion DSN structures. Oracle databases have many special things that need to be learned and understood in depth. This article is just a simple description of some basic knowledge, A simple understanding of PDO.

[References]
PHP 5 Data Object (PDO) abstraction layer and Oracle
PDO Functions

What is PDO?
The POD (PHP Data Object) extension is added to PHP5. The PDO connection is identified by default in PHP6.DatabaseAll non-PDO extensions will be removed from the extension in PHP6. This extension provides PHP built-in PDO class for accessing the database. Different databases use the sameMethodTo solve the problem of inconsistent database connections.
I configured it for development in windows.
■ PDO goals
A lightweight, clear, and convenient API is provided to unify the common features of different RDBMS libraries, but more advanced features are not excluded. PHP scripts provide optional abstract/compatibility.
■ Features of PDO:
Performance. From the very beginning, PDO learned from the success and failure of existing database expansion. Because PDO'sCodeIs brand new, so we have the opportunity to design performance again to take advantage of the latest features of PHP 5. Capability. PDO is designed to provide common database functions as the basis and provide convenient access to the unique functions of RDBMS. Simple. PDO is designed to make it easy to use databases. The API does not forcibly intervene in your code and clearly shows the process of calling each function. It can be expanded during runtime. PDO extensions are modular, allowing you to load drivers at the backend of your database at runtime without re-compiling or re-compiling.InstallThe entire PHP program. For example, the PDO_OCI extension replaces the PDO extension implementation.OracleDatabase API. There are also someMySQL, PostgreSQL, ODBC and Firebird drivers, more drivers are still under development.
■ Install PDO
I am using the PDO extension for WINDOWS development. If you wantLinuxTo install the configuration, go to another location.
Version requirements:
Php5.1 and later versions are included in the program package;
Php5.0.x is downloaded to pecl.php.net and put it in your extension library, which is the ext folder of the PHP folder;
In the manual, versions earlier than 5.0 cannot run PDO extensions.
Configuration:
Modify Your php. ini configuration file to support pdo. (php. if you do not understand ini, first make it clear that you need to modify the php code displayed by calling your phpinfo () function. ini)
Set
Remove the semicolon before extension = php_pdo.dll, which is the annotation symbol of the php configuration file. This extension is required.
Down
; Extension = php_pdo.dll
; Extension = php_pdo_firebird.dll
; Extension = php_pdo_informix.dll
; Extension = php_pdo_mssql.dll
; Extension = php_pdo_mysql.dll
; Extension = php_pdo_oci.dll
; Extension = php_pdo_oci8.dll
; Extension = php_pdo_odbc.dll
; Extension = php_pdo_pgsql.dll
; Extension = php_pdo_sqlite.dll
The databases corresponding to each extension are:
Driver nameSupported databasesPDO_DBLIBFreeTDS/Microsoft SQL Server/SybasePDO_FIREBIRDFirebird/Interbase 6PDO_INFORMIXIBMInformix Dynamic ServerPDO_MYSQLMySQL 3.x/ 4. xPDO_OCIOracle Call InterfacePDO_ODBCODBC v3 (IBM DB2, unixODBC and win32 ODBC) pdo_pgsql1_sqlpdo_sqlitesqlite 3 and SQLite 2
You only need to remove the annotator ";" before the corresponding extension to which database you want to use.
Use PDO
Let me assume that you have installed mysql. If you haven't installed MySQL, try to install it first. mysql5.0.22 is for me, And mysql4.0.26 is for night travelers.
Database connection:
We use the following example to analyze how PDO connects to the database,

<? Php
$ Dbms = 'mysql'; // Database Type: Oracle uses ODI. for developers, if they use different databases, they do not need to remember so many functions.
$ Host = 'localhost'; // Database host Name
$ DbName = 'test'; // database used
$ User = 'root'; // database connection username
$ Pass = ''; // Password
$ Dsn = "$ dbms: host = $ host; dbname = $ dbName ";
//
Try {
$ Dbh = newPDO ($ dsn, $ user, $ pass); // initialize a PDO object, that is, create a database connection object $ dbh
Echo "connection successful <br/> ";
/* You can perform a search operation.
Foreach ($ dbh-> query ('select * from foo') as $ row ){
Print_r ($ row); // you can use echo ($ GLOBAL); to view these values
}
*/
$ Dbh = null;
} Catch (PDOException $ e ){
Die ("Error! : ". $ E-> getMessage ()." <br/> ");
}
// By default, this is not a persistent connection. If you need a persistent connection to the database, you need to add the following parameter: array (PDO: ATTR_PERSISTENT => true:
$ Db = newPDO ($ dsn, $ user, $ pass, array (PDO: ATTR_PERSISTENT => true ));
?>

Database Query:
We have performed a query above, and we can also use the following query:

<? Php
$ Db-> setAttribute (PDO: ATTR_CASE, PDO: CASE_UPPER); // set attributes
$ Rs = $ db-> query ("SELECT * FROM foo ");
$ Rs-> setFetchMode (PDO: FETCH_ASSOC );
$ Result_arr = $ rs-> fetchAll ();
Print_r ($ result_arr );
?>

Because the setAttribute () method is used, place the two parameters and forcibly convert the field name to uppercase. The following lists the parameters with multiple PDO: setAttribute:

  • PDO: ATTR_CASE: force the column name to a format, as detailed below (second parameter ):
    • PDO: CASE_LOWER: the column name must be in lower case.
    • PDO: CASE_NATURAL: column names follow the original method
    • PDO: CASE_UPPER: Force column names to be uppercase.
  • PDO: ATTR_ERRMODE: error message.
    • PDO: ERRMODE_SILENT: only error codes are displayed.
    • PDO: ERRMODE_WARNING: displays a warning error.
    • PDO: ERRMODE_EXCEPTION: throw an exception.
  • PDO: ATTR_ORACLE_NULLS (not only effective in ORACLE, but also in other databases): Specifies the value of the NULL value returned by the database in php.
    • PDO: NULL_NATURAL: Unchanged.
    • PDO: NULL_EMPTY_STRING: Empty string is converted toNULL.
    • PDO: NULL_TO_STRING: NULL is converted to an empty string.
  • PDO: ATTR_STRINGIFY_FETCHES: Convert numeric values to strings when fetching. Requires bool.
  • PDO: ATTR_STATEMENT_CLASS: Set user-supplied statement class derived from PDOStatement. Cannot be used with persistent PDO instances. Requiresarray (string classname, array (mixed constructor_args )).
  • PDO: ATTR_AUTOCOMMIT (available in OCI, Firebird and MySQL): Whether to autocommit every single statement.
  • PDO: MYSQL_ATTR_USE_BUFFERED_QUERY (available in MySQL): Use buffered queries.

In the example, $ rs-> setFetchMode (PDO: FETCH_ASSOC); is PDOStatement: setFetchMode (), which declares the return type.
There are:
PDO: FETCH_ASSOC -- join array form
PDO: FETCH_NUM -- numeric index array format
PDO: FETCH_BOTH -- both arrays are available, which is the default
PDO: FETCH_OBJ -- followObjectSimilar to the previous mysql_fetch_object ()
For more information about the return type declaration (PDOStatement: method name), see the manual.
★Insert, update, and delete data,

$ Db-> exec ("delete from 'xxxx _ menu 'where mid = 43 ");

SimpleSummaryThe above operations:
Query operations are mainly PDO: query (), PDO: exec (), PDO: prepare ().
PDO: query () is mainly used for operations that return records, especially SELECT operations,
PDO: exec () is mainly used for operations that do not return result sets, such as INSERT, UPDATE, DELETE, and so on. It returns the number of columns affected by the current operation.
PDO: prepare () is mainly used for preprocessing. You need to use $ rs-> execute () to execute the SQL statements in the preprocessing. This method can bind parameters and has powerful functions, this document is not a simple description. You can refer to the Manual and other documents.
To obtain a result set, perform the following operations: PDOStatement: fetchColumn (), PDOStatement: fetch (), and PDOStatement: fetchALL ().
PDOStatement: fetchColumn () is a field of the first record specified in the result. The default value is the first field.
PDOStatement: fetch () is used to obtain a record,
PDOStatement: fetchAll () is to obtain all the record sets to one. You can use PDOStatement: setFetchMode to set the type of the desired result set.
There are also two peripheral operations: PDO: lastInsertId () and PDOStatement: rowCount (). PDO: lastInsertId () is the last insert operation, and the primary key column type is the last auto-increment ID of auto-increment.
PDOStatement: rowCount () is the result set affected by the DELETE, INSERT, and UPDATE operations on PDO: query () and PDO: prepare :: the exec () method and SELECT operation are invalid.
Transactions and automatic submission
So far, you have connected to mysql through PDO. Before sending a query, you should understand how PDO manages transactions. If you have never touched on a transaction before, you must first understand the four features of the transaction: Atomicity, Consistency, Isolation, and Durability ), ACID. In layman's words, for any execution in a transactionWorkEven if it is executed in stages, it will ensure that the work will be securely applied to the database and will not be affected by other connections when the work is submitted. Transactional work can be automatically revoked based on the request (assuming you have not submitted it), which makes it easier to handle errors in the script.
Transactions are usually implemented by saving up a batch of changes to make them take effect at the same time. This can greatly improve the efficiency of these updates. In other words, a transaction can make the script faster and more robust (but you need to use the transaction correctly to get this benefit ).
Unfortunately, not every database supports transactions (Mysql5 supports transactions, I don't know about mysql4), so when the connection is opened for the first time, PDO needs to run in the so-called "auto-commit" mode. The automatic commit Mode means that if the database supports transactions, each query you run has its own implicit transaction. If the database does not support transactions, no such transaction exists for each query. If you need a transaction, you must use the PDO: beginTransaction () method to start a transaction. If the underlying driver does not support transactions, a PDOException will be thrown (regardless of the error processing settings: This is always a serious error state ). In a transaction, you can use PDO: commit () or PDO: rollBack () to end the transaction, depending on whether the code running in the transaction is successful.
When the script ends, or when a connection is about to be closed, if there is an unfinished transaction, PDO will automatically roll back the transaction. This is a security measure that helps avoid inconsistencies when the script ends abnormally-if the transaction is not explicitly committed, it is assumed that there will be inconsistencies somewhere, therefore, perform rollback to ensure data security.

// Example from http://www.ibm.com/developerworks/cn/db2/library/techarticles/dm-0505furlong/index.html
Try {
$ Dbh = new PDO ('odbc: sample', 'db2inst1', 'ibmdb ',
Array (PDO_ATTR_PERSISTENT => true ));
Echo "Connected \ n ";
$ Dbh-> setAttribute (PDO_ATTR_ERRMODE, PDO_ERRMODE_EXCEPTION );
$ Dbh-> beginTransaction ();
$ Dbh-> exec ("insert into staff (id, first, last) values (23, 'job', 'bloggs ')");
$ Dbh-> exec ("insert into salarychange (id, amount, changedate)
Values (23,500 00, NOW ())");
$ Dbh-> commit ();
} Catch (Exception $ e ){
$ Dbh-> rollBack ();
Echo "Failed:". $ e-> getMessage ();
}

In the preceding example, assume that we create a group of entries for a new employee. This employee has an ID number, that is, 23. In addition to entering the basic data of this person, we also need to record the employee's salary. The two updates are easy to complete, but by including the two updates in the beginTransaction () and commit () calls, you can ensure that others cannot see the changes before the changes are completed. If an error occurs, the catch block can roll back all the changes that have occurred since the beginning of the transaction and print an error message.
It is not necessary to update the transaction. You can also issue complex queries to extract data, and use that information to create more updates and queries. When the transaction is inActivityYou can ensure that others cannot make changes during work. In fact, this is not 100% correct, but if you did notHeardIf you have performed a transaction, this introduction is not a problem.
Pre-processing statements and stored procedures
Many more mature databases support the concept of pre-processing statements. What is a pre-processing statement? You can regard the pre-processing statement as a compiled template of the SQL statement you want to run. It can be customized using variable parameters. Preprocessing statements can bring two benefits:

  • The query only needs to be parsed (or prepared) once, but can be executed multiple times with the same or different parameters. When the query is ready, the database will analyze, compile, and optimize the plan for executing the query. For complex queries, this process takes a long time. If you need to repeat the same query multiple times with different parameters, this process will greatly reduce the speed of the application. By using preprocessing statements, you can avoid repeated analysis, compilation, and optimization cycles. In short, preprocessing statements use fewer resources and therefore run faster.
  • Parameters provided to the pre-processing statement do not need to be enclosed in quotation marks. The driver will process these parameters. If the application exclusively uses preprocessing statements, it can ensure that no SQL intrusion occurs. (However, if you still establish other parts of the query on untrusted input, there is still a risk ).

Preprocessing statements are so useful that PDO actually breaks the Rule Set in Objective 4: If the driver does not support preprocessing statements, PDO will simulate preprocessing statements.
Example of a PDO application:

<? Php
$ Dbms = 'mysql'; // Database Type: Oracle uses ODI. for developers, if they use different databases, they do not need to remember so many functions.
$ Host = 'localhost'; // Database host Name
$ DbName = 'test'; // database used
$ User = 'root'; // database connection username
$ Pass = ''; // Password
$ Dsn = "$ dbms: host = $ host; dbname = $ dbName ";
ClassdbextendsPDO {
Publicfunction _ construct (){
Try {
Parent: :__ construct ("$ GLOBALS [dsn]", $ GLOBALS ['user'], $ GLOBALS ['pass']);
} Catch (PDOException $ e ){
Die ("Error:". $ e->__ toString (). "<br/> ");
}
}
Publicfinalfunctionquery ($ SQL ){
Try {
Returnparent: query ($ this-> setString ($ SQL ));
} Catch (PDOException $ e ){
Die ("Error:". $ e->__ toString (). "<br/> ");
}
}
PrivatefinalfunctionsetString ($ SQL ){
Echo "I want to handle $ SQL ";
Return $ SQL;
}
}
$ Db = newdb ();
$ Db-> setAttribute (PDO: ATTR_CASE, PDO: CASE_UPPER );
Foreach ($ db-> query ('select * from xxxx_menu ') as $ row ){
Print_r ($ row );
}
$ Db-> exec ('delete FROM 'xxxx _ menu 'where mid = 43 ');
?>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.