Currently, there is a long way to go to implement the "database abstraction layer". Using a "database access abstraction layer" like PDO is a good choice.
PDO contains three predefined classes
PDO contains three predefined classes, which are PDO, PDOStatement and PDOException.
1. PDO
PDO->beginTransaction() - Indicates the starting point of rollback
PDO->commit() - Indicates the end point of rollback and executes SQL
PDO->__construct() — Create an instance of PDO link database
PDO->errorCode() — Get the error code
PDO->errorInfo() — Get the error information
PDO- >exec() — Process a SQL statement and return the number of entries affected
PDO->getAttribute() — Get the attributes of a "database connection object"
PDO->getAvailableDrivers() — Get Valid PDO drive name
PDO->lastInsertId() — Get the primary key value of the last piece of data written
PDO->prepare() — Generate a "query object"
PDO-> ;query() — Process a SQL statement and return a "PDOStatement"
PDO->quote() — Add quotation marks to a string in a SQL
PDO->rollBack() — Execute return Roll
PDO->setAttribute() — Set attributes for a "database connection object"
2. PDOStatement
PDOStatement->bindColumn() — Bind a column to a PHP variable
PDOStatement->bindParam() — Binds a parameter to the specified variable name
PDOStatement->bindValue() — Binds a value to a parameter
PDOStatement->closeCursor() — Closes the cursor, enabling the statement to be executed again.
PDOStatement->columnCount() — Returns the number of columns in the result set
PDOStatement->errorCode() — Fetch the SQLSTATE associated with the last operation on the statement handle
PDOStatement->errorInfo() — Fetch extended error information associated with the last operation on the statement handle
PDOStatement->execute() — Executes a prepared statement
PDOStatement-> fetch() — Fetches the next row from a result set
PDOStatement->fetchAll() — Returns an array containing all of the result set rows
PDOStatement->fetchColumn() — Returns a single column from the next row of a result set
PDOStatement->fetchObject() — Fetches the next row and returns it as an object.
PDOStatement->getAttribute() — Retrieve a statement attribute
PDOStatement-> getColumnMeta() — Returns metadata for a column in a result set
PDOStatement->nextRowset() — Advances to the next rowset in a multi-rowset statement handle
PDOStatement->rowCount() — Returns the number of rows affected by the last SQL statement
PDOStatement->setAttribute() — Set a statement attribute
PDOStatement->setFetchMode() — Set the default fetch mode for this statement
PDO is A "database access abstraction layer" is used to unify the access interfaces of various databases. Compared with the function libraries of mysql and mysqli, PDO makes cross-database use more friendly; compared with ADODB and MDB2, PDO is more efficient. At present, there is a long way to go to implement the "database abstraction layer". Using a "database access abstraction layer" such as PDO is a good choice.
PDO contains three predefined classes
PDO contains three predefined classes, which are PDO, PDOStatement and PDOException.
1. PDO
PDO->beginTransaction() - Indicates the starting point of rollback
PDO->commit() - Indicates the end point of rollback and executes SQL
PDO->rollBack() — Perform rollback
PDO->__construct() — Create an instance of PDO link database
PDO->errorCode() — Get the error code
PDO-> ;errorInfo() — Get error information
PDO->exec() — Process a SQL statement and return the number of entries affected
PDO->getAttribute() — Get a "database connection object" Properties
PDO->getAvailableDrivers() — Get the valid PDO driver name
PDO->lastInsertId() — Get the primary key value of the last piece of data written
PDO->prepare( ) — Generate a "query object"
PDO->query() — Process a SQL statement and return a "PDOStatement"
PDO->quote() — Add to a string in a SQL Quotation marks
PDO->setAttribute() — Set attributes for a "database connection object"
Detailed explanation 1) Database connection in PDO
$dsn = 'mysql:dbname=ent;host =127.0.0.1′;
$user = 'root';
$password = '123456';
try {
$dbh = new PDO($dsn, $user, $password, array (PDO::ATTR_PERSISTENT => true));
$dbh->query('set names utf8;');
foreach ($dbh->query('SELECT * from tpm_juese') as $row) {
print_r($row);
}
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
Many web applications will be optimized by using persistent connections to the database. The persistent connection is not closed at the end of the script,
Instead it is cached and reused when another script requests a connection with the same ID.
The cache of persistent connections allows you to avoid the resource consumption of deploying a new connection every time the script needs to talk to the database, making your web application faster.
The array(PDO::ATTR_PERSISTENT => true) in the above example is to set the connection type to a persistent connection.
Detailed explanation 2) Transactions in PDO
PDO->beginTransaction(), PDO->commit(), PDO->rollBack() are the three methods when the rollback function is supported used together. The PDO->beginTransaction() method marks the starting point, the PDO->commit() method marks the rollback end point and executes SQL, and PDO->rollBack() performs rollback.
try {
$dbh = new PDO('mysql:host=localhost;dbname=test', 'root', ”);
$dbh->query( 'set names utf8;');
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh->beginTransaction();
$dbh- >exec("INSERT INTO `test`.`table` (`name` ,`age`)VALUES ('mick', 22);");
$dbh->exec("INSERT INTO `test `.`table` (`name` ,`age`)VALUES ('lily', 29);”);
$dbh->exec(”INSERT INTO `test`.`table` (`name` ,`age`)VALUES ('susan', 21);”);
$dbh->commit();
} catch (Exception $e) {
$dbh-> ;rollBack();
echo "Failed: " . $e->getMessage();
}
?>
Now that you have established the connection through PDO, before deploying the query you You must understand how PDO manages transactions. If you have never encountered transaction processing before, (now a brief introduction:) they provide 4 main features: Atomicity, Consistency, Independence and Durability (Atomicity) , Consistency, Isolation and Durability (ACID) In ??layman's terms, when all work in a transaction is submitted, even if it is executed in stages, it must be safely applied to the database and not be interfered with by other connections. It can be easily automatically canceled when an error occurs in the request. The typical use of transactions is to "save" batch changes and then execute them immediately. In other words, this will completely improve the efficiency of updates. , transactions can make your scripts faster and potentially more robust (to achieve this advantage you still need to use them correctly)
Unfortunately, not every database supports transactions, so PDO is required. Running in what is considered "autocommit" mode when establishing a connection Autocommit mode means that every query you execute has its own implicit transaction processing, whether the database supports transactions or does not exist because the database does not. affairs. If you need a transaction, you must create one using the PDO->beginTransaction() method. If the underlying driver does not support transactions, a PDOException will be thrown (regardless of your exception handling settings, since this is always a serious error condition). Within a transaction, you can end it using PDO->commit() or PDO->rollBack(), depending on whether the code in the transaction ran successfully.
When the script ends or a connection is to be closed, if you still have an unfinished transaction, PDO will automatically roll it back. This is a safe solution in case the script terminates unexpectedly - if you don't explicitly commit the transaction, it will assume that something went wrong and perform a rollback for the safety of your data.
2. PDOStatement
PDOStatement->bindColumn() — Bind a column to a PHP variable
PDOStatement->bindParam() — Binds a parameter to the specified variable name
PDOStatement->bindValue() — Binds a value to a parameter
PDOStatement->closeCursor() — Closes the cursor, enabling the statement to be executed again.
PDOStatement->columnCount() — Returns the number of columns in the result set
PDOStatement->errorCode() — Fetch the SQLSTATE associated with the last operation on the statement handle
PDOStatement->errorInfo() — Fetch extended error information associated with the last operation on the statement handle
PDOStatement->execute() — Executes a prepared statement
PDOStatement->fetch() — Fetches the next row from a result set
PDOStatement->fetchAll() — Returns an array containing all of the result set rows
PDOStatement->fetchColumn() — Returns a single column from the next row of a result set
PDOStatement->fetchObject() — Fetches the next row and returns it as an object.
PDOStatement->getAttribute() — Retrieve a statement attribute
PDOStatement->getColumnMeta() — Returns metadata for a column in a result set
PDOStatement->nextRowset() — Advances to the next rowset in a multi-rowset statement handle
PDOStatement->rowCount() — Returns the number of rows affected by the last SQL statement
PDOStatement->setAttribute() — Set a statement attribute
PDOStatement->setFetchMode() — Set the default fetch mode for this statement
三、PDOException
PDO 提供了3中不同的錯誤處理策略。
1. PDO::ERRMODE_SILENT
這是默認(rèn)使用的模式。PDO會在statement和database對象上設(shè)定簡單的錯誤代號,你可以使用PDO->errorCode() 和 PDO->errorInfo() 方法檢查錯誤;如果錯誤是在對statement對象進(jìn)行調(diào)用時導(dǎo)致的,你就可以在那個對象上使用 PDOStatement->errorCode() 或 PDOStatement->errorInfo() 方法取得錯誤信息。而如果錯誤是在對database對象調(diào)用時導(dǎo)致的,你就應(yīng)該在這個database對象上調(diào)用那兩個方法。
2. PDO::ERRMODE_WARNING
作為設(shè)置錯誤代號的附加,PDO將會發(fā)出一個傳統(tǒng)的E_WARNING信息。這種設(shè)置在除錯和調(diào)試時是很有用的,如果你只是想看看發(fā)生了什么問題而不想中斷程序的流程的話。
3. PDO::ERRMODE_EXCEPTION
作為設(shè)置錯誤代號的附件,PDO會拋出一個PDOException異常并設(shè)置它的屬性來反映錯誤代號和錯誤信息。這中設(shè)置在除錯時也是很有用的,因為他會有效的“放大(blow up)”腳本中的出錯點,非??焖俚闹赶蛞粋€你代碼中可能出錯區(qū)域。(記?。喝绻惓?dǎo)致腳本中斷,事務(wù)處理回自動回滾。)
異常模式也是非常有用的,因為你可以使用比以前那種使用傳統(tǒng)的PHP風(fēng)格的錯誤處理結(jié)構(gòu)更清晰的結(jié)構(gòu)處理錯誤,比使用安靜模式使用更少的代碼及嵌套,也能夠更加明確地檢查每個數(shù)據(jù)庫訪問的返回值。
關(guān)于PHP中異常的更多信息請看Exceptions章節(jié)
PDO 使用基于SQL-92 SQLSTATE 的錯誤代號字符串;特定的PDO驅(qū)動應(yīng)當(dāng)將自己本身的代號對應(yīng)到適當(dāng)?shù)腟QLSTATE代號上。PDO->errorCode() 方法只返回單一的SQLSTATE代號。如果你需要關(guān)于一個錯誤的更加有針對性的信息,PDO也提供了一個PDO->errorInfo()方法,它可以返回一個包含了SQLSTATE代號,特定數(shù)據(jù)庫驅(qū)動的錯誤代號和特定數(shù)據(jù)庫驅(qū)動的錯誤說明字符串。
// 修改默認(rèn)的錯誤顯示級別
$dbh->setAttribute(PDO::ATTR_ERRMODE,?PDO::ERRMODE_WARNING);
?>
屬性列表:
PDO::PARAM_BOOL
Represents a Boolean type
PDO::PARAM_NULL
Represents a NULL type in SQL
PDO::PARAM_INT
Represents an INTEGER type in SQL
PDO::PARAM_STR
represents a SQL CHAR, VARCHAR type in SQL
PDO::PARAM_LOB
represents a large object type in SQL
PDO::PARAM_STMT
represents a SQL The recordset type is not supported yet
PDO::PARAM_INPUT_OUTPUT
Specifies that the parameter is an INOUT parameter for a stored procedure. Youmust bitwise-OR this value with an explicit PDO::PARAM_* data type.
PDO::FETCH_LAZY
Return each row of results as an object
PDO::FETCH_ASSOC
Only returns the result set of the query with the key value as the subscript. Data with the same name only returns one
PDO ::FETCH_NAMED
Only returns the result set of the query with the key value as the subscript, and the data with the same name is returned in the form of an array
PDO::FETCH_NUM
Only returns the result set of the query with the number as the subscript
PDO::FETCH_BOTH
Returns the result set of the query with key value and number as subscript at the same time
PDO::FETCH_OBJ
Returns the result set in the form of an object
PDO::FETCH_BOUND
will The value bound to PDOStatement::bindParam() and PDOStatement::bindColumn() is returned as a variable name after assignment
PDO::FETCH_COLUMN
means that only a certain column in the result set is returned
PDO::FETCH_CLASS
Indicates that the result set is returned in the form of a class
PDO::FETCH_INTO
Indicates that the data is merged into an existing class and returned
PDO::FETCH_FUNC
PDO::FETCH_GROUP
PDO ::FETCH_UNIQUE
PDO::FETCH_KEY_PAIR
Return the result set in the form of the first key value and the following numbers
PDO::FETCH_CLASSTYPE
PDO::FETCH_SERIALIZE
means that the data will be Merge into an existing class and serialize it back
PDO::FETCH_PROPS_LATE
Available since PHP 5.2.0
PDO::ATTR_AUTOCOMMIT
When set to true, PDO will automatically try to stop accepting Delegate, start execution
PDO::ATTR_PREFETCH
Set the data size obtained by the application in advance, not all databases support it
PDO::ATTR_TIMEOUT
Set the value of the connection database timeout
PDO ::ATTR_ERRMODE
Set the Error processing mode
PDO::ATTR_SERVER_VERSION
Read-only attribute, indicating the server-side database version of the PDO connection
PDO::ATTR_CLIENT_VERSION
Read-only attribute, indicating the PDO connection Client PDO driver version
PDO::ATTR_SERVER_INFO
Read-only attribute, indicating the meta information of the server connected to PDO
PDO::ATTR_CONNECTION_STATUS
PDO::ATTR_CASE
Through PDO::CASE_ The contents in * operate on the form of columns
PDO::ATTR_CURSOR_NAME
Get or set the name of the pointer
PDO::ATTR_CURSOR
Set the type of the pointer, PDO now supports PDO::CURSOR_FWDONLY and PDO::CURSOR_FWDONLY
PDO::ATTR_DRIVER_NAME
Returns the name of the PDO driver used
PDO::ATTR_ORACLE_NULLS
Convert the returned empty string to SQL NULL
PDO::ATTR_PERSISTENT
Get an existing connection
PDO::ATTR_STATEMENT_CLASS
PDO::ATTR_FETCH_CATALOG_NAMES
In the returned result set, use custom catalog names instead of field names.
PDO::ATTR_FETCH_TABLE_NAMES
In the returned result set, use custom table names instead of field names.
PDO::ATTR_STRINGIFY_FETCHES
PDO::ATTR_MAX_COLUMN_LEN
PDO::ATTR_DEFAULT_FETCH_MODE
Available since PHP 5.2.0
PDO::ATTR_EMULATE_PREPARES
Available since PHP 5.1.3.
PDO::ERRMODE_SILENT
Does not report any error message when an error occurs, which is the default value
PDO::ERRMODE_WARNING
Sends a php E_WARNING message when an error occurs
PDO::ERRMODE_EXCEPTION
Throws a PDOException when an error occurs
PDO::CASE_NATURAL
Default display format of the reply column
PDO::CASE_LOWER
Force the column name to be lowercase
PDO::CASE_UPPER
Force the column The name is capitalized
PDO::NULL_NATURAL
PDO::NULL_EMPTY_STRING
PDO::NULL_TO_STRING
PDO::FETCH_ORI_NEXT
Get the next row of data in the result set, only valid when there is a pointer function
PDO::FETCH_ORI_PRIOR
Get the previous row of data in the result set, which is only valid when there is a pointer function.
PDO::FETCH_ORI_FIRST
Get the first row of data in the result set, which is only valid when there is a pointer function.
PDO::FETCH_ORI_LAST
Get the last row of data in the result set, which is only valid when the pointer function is available
PDO::FETCH_ORI_ABS
Get the last row of data in the result set, which is only valid when the pointer function is available
PDO::FETCH_ORI_REL
Get the data of a row after the current row in the result set. It is only valid when there is a pointer function.
PDO::CURSOR_FWDONLY
Create a backward-only pointer operation object
PDO::CURSOR_SCROLL
Create a pointer operation object and pass the content in PDO::FETCH_ORI_* to control the result set
PDO::ERR_NONE (string)
Set the error message when there is no error
PDO::PARAM_EVT_ALLOC
Allocation event
PDO::PARAM_EVT_FREE
Deallocation event
PDO::PARAM_EVT_EXEC_PRE
Event?triggered?prior?to?execution?of?a?prepared?statement.
PDO::PARAM_EVT_EXEC_POST
Event?triggered?subsequent?to?execution?of?a?prepared?statement.
PDO::PARAM_EVT_FETCH_PRE
Event?triggered?prior?to?fetching?a?result?from?a?resultset.
PDO::PARAM_EVT_FETCH_POST
Event?triggered?subsequent?to?fetching?a?result?from?a?resultset.
PDO::PARAM_EVT_NORMALIZE
Event?triggered?during?bound?parameter?registration?allowing?the?driver?to?normalize?the?parameter?name.
更多PHP PDO函數(shù)庫詳解相關(guān)文章請關(guān)注PHP中文網(wǎng)!

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)
