Home > Article > Backend Development > Detailed explanation of PDO class in PHP5
This article mainly introduces the detailed explanation of the PDO class in PHP5. Interested friends can refer to it. I hope it will be helpful to everyone.
■What is PDO? The POD (PHP Data Object) extension was added in PHP5. PDO will be used by default to connect to the database in PHP6. All non-PDO extensions will be removed from the extension in PHP6. This extension provides PHP built-in class PDO to access the database. Different databases use the same method name to solve the problem of inconsistent database connections. I configured it for development under windows. ■The goal of PDO
Provide a lightweight, clear, and convenient API
Unify the common features of various different RDBMS libraries, but does not exclude more advanced features.
Provides an optional greater degree of abstraction/compatibility via PHP scripts.
■PDO features:
Performance. PDO learned from the beginning about the successes and failures of scaling existing databases. Because PDO's code is brand new, we have the opportunity to redesign performance from the ground up to take advantage of PHP 5's latest features.
ability. PDO is designed to provide common database functionality as a foundation while providing easy access to the unique features of an RDBMS.
Simple. PDO is designed to make working with databases easy for you. The API doesn't force its way into your code and makes it clear what each function call does.
Extensible at runtime. The PDO extension is modular, enabling you to load drivers for your database backend at runtime without having to recompile or reinstall the entire PHP program. For example, the PDO_OCI extension implements the oracle database API instead of the PDO extension. There are also drivers for MySQL, PostgreSQL, ODBC, and Firebird, with more in development. [separator]
■Installing PDO
Here is the PDO extension for development under WINDOWS. If you want to install and configure it under Linux, please look elsewhere.
Version requirements: php5.1 and later versions are already included in the package; php5.0.x needs to be downloaded from pecl.php.net and placed in your extension library, which is the ext of the folder where PHP is located. folder; the manual says that versions before 5.0 cannot run PDO extensions. Configuration:
Modify your php.ini configuration file so that it supports pdo. (If you don’t understand php.ini, first make it clear that you need to modify the php.ini displayed when calling your phpinfo() function. ) Remove the semicolon in front of extension=php_pdo.dll. The semicolon is the php configuration file comment symbol. This extension is necessary. Further down there are
;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 corresponding to each extension The databases are:
Driver name Supported databases
PDO_DBLIB FreeTDS / Microsoft SQL Server / Sybase
PDO_FIREBIRD Firebird/Interbase 6
PDO_INFORMIX IBM Informix Dynamic Server
PDO_MYSQL MySQL 3.x/4.x
PDO_OCI Oracle Call Interface
PDO_ODBC ODBC v3 (IBM DB2, unixODBC and win32 ODBC)
PDO_PGSQL PostgreSQL
PDO_SQLITE SQLite 3 and SQLite 2
Which database you want to use, just add the corresponding extension Just remove the comment symbol ";" in front of it.
■Using PDO
I assume here that you have installed mysql. If not, please find a way to install it first. Mine is mysql5.0.22, and the passerby in the dark uses MySQL 4.0.26. Also available.
★Database connection:
We use the following example to analyze PDO connection to the database,
$dbms='mysql'; //Database type oracle Using ODI, for developers, if they use different databases, they only need to change this, and there is no need to remember so many functions.
$host='localhost'; //Database host name
$dbName='test' ; //Database used
$user='root'; //Database connection username
$pass=''; //Corresponding password
$dsn="$dbms:host=$host ;dbname=$dbName";
//
try {
$dbh = new PDO($dsn, $user, $pass); //Initializing a PDO object means creating a database Connection object $dbh
echo "Connection successful
";
/*You can also perform a search operation
foreach ($dbh->query('Select * from FOO') as $row) {
print_r($row);
} catch (PDOException $e) {
die ("Error!: " . $e->getMessage() . "
");
}
// By default, this is not a long connection. If you need a long connection to the database, you need to add a parameter at the end: array(PDO::ATTR_PERSISTENT => true), which becomes like this:
$db = new PDO($dsn, $user, $pass , array(PDO::ATTR_PERSISTENT => true));
?>
★Database query:
We have already conducted a query above, we can still Use the following query:
$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 of the above Use the setAttribute() method, put those two parameters, and force the field name to uppercase. The following lists the parameters of PDO::setAttribute(): PDO::ATTR_CASE: Forces the column name to become a format, the details are as follows (second parameter):
PDO::CASE_LOWER: Forces the column name The name is lowercase.
PDO::CASE_NATURAL: The column name is in the original way
PDO::CASE_UPPER: The column name is forced to be uppercase.
PDO::ATTR_ERRMODE: Error Tip.
PDO::ERRMODE_SILENT: Does not display error message, only error code.
PDO::ERRMODE_WARNING: Displays warning error.
PDO::ERRMODE_EXCEPTION: Throw An exception occurred.
PDO::ATTR_ORACLE_NULLS (valid not only for ORACLE, but also for other databases): ) Specify the corresponding value in php for the NULL value returned by the database.
PDO::NULL_NATURAL: unchanged.
PDO::NULL_EMPTY_STRING: Empty string is converted to NULL.
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. Requires array(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.
$rs->setFetchMode(PDO::FETCH_ASSOC); in the example is PDOStatement::setFetchMode(), a declaration of the return type.
are as follows:
PDO::FETCH_ASSOC -- Associative array form
PDO::FETCH_NUM -- Numeric index array form
PDO::FETCH_BOTH -- Both array forms are available, which is missing Provincial
PDO::FETCH_OBJ -- According to the form of the object, similar to the previous mysql_fetch_object()
For more return type declarations (PDOStatement::method name), see the manual.
★Insert, update, delete data,
$db->exec("Delete FROM `xxxx_menu` where mid=43");
Simple To summarize the above operations:
The query operations are mainly PDO::query(), PDO::exec(), PDO::prepare().
PDO::query() is mainly used for operations that return recorded results, especially Select operations.
PDO::exec() is mainly used for operations that do not return a result set, such as Insert, Update, and Delete For other operations, the result it returns is the number of columns affected by the current operation.
PDO::prepare() is mainly a preprocessing operation. You need to use $rs->execute() to execute the SQL statement in the preprocessing. This method can bind parameters and has a relatively powerful function. This article cannot simply describe it. If you understand, you can refer to the manual and other documents.
The main operations for obtaining the result set are: PDOStatement::fetchColumn(), PDOStatement::fetch(), PDOStatement::fetchALL().
PDOStatement::fetchColumn() is a field of the first record specified in the fetch result. The default is the first field.
PDOStatement::fetch() is used to obtain a record,
PDOStatement::fetchAll() is used to obtain all record sets into one. To obtain the results, you can set the type of the required result set through PDOStatement::setFetchMode.
There are two other peripheral operations, one is PDO::lastInsertId() and PDOStatement::rowCount(). PDO::lastInsertId() returns the last insertion operation, and the primary key column type is the last auto-increment ID.
PDOStatement::rowCount() is mainly used for the result set affected by PDO::query() and PDO::prepare()'s Delete, Insert, and Update operations. It is invalid for the PDO::exec() method and Select operation. .
Related recommendations:
The reason why connecting mysql through PDO can prevent injection
ThinkPHP framework based on PDO method to connect database operation example
Example of PDO transaction processing operation in PHP
The above is the detailed content of Detailed explanation of PDO class in PHP5. For more information, please follow other related articles on the PHP Chinese website!