PHP PDO library

  • 2020-03-31 20:34:17
  • OfStack

For now, implementing a "database abstraction layer" is a long way off, and using a "database access abstraction layer" like PDO is a good choice.

The PDO contains three predefined classes

PDO contains three predefined classes: PDO, PDOStatement, and PDOException.

A, the PDO

The PDO - > BeginTransaction () - indicates the beginning point of the rollback
The PDO - > Commit () - indicates the end of the rollback and executes the SQL
The PDO - > S/s - build an instance of the pdo-linked database
The PDO - > ErrorCode () - gets the errorCode
The PDO - > ErrorInfo () - gets the wrong information
The PDO - > Exec () - processes an SQL statement and returns the number of entries affected
The PDO - > GetAttribute () - gets an attribute of a database connection object
The PDO - > GetAvailableDrivers () - gets the valid PDO driver name
The PDO - > LastInsertId () - gets the primary key value of the last data written
The PDO - > Prepare () - generates a "query object"
The PDO - > Query () - processes an SQL statement and returns a "PDOStatement"
The PDO - > Quote () - adds quotes to a string in SQL
The PDO - > RollBack () - performs a rollBack
The PDO - > SetAttribute () - sets attributes for a database connection object

Second, the 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 () -- execute a prepared statement
PDOStatement - > Fetch () -- fetch 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", which is used to unify the access interface of various databases. Compared with the function libraries of mysql and mysqli, PDO makes the use of cross-database more affinity. PDO is more efficient than ADODB and MDB2. For now, implementing a "database abstraction layer" is a long way off, and using a "database access abstraction layer" like PDO is a good choice.

The PDO contains three predefined classes

PDO contains three predefined classes: PDO, PDOStatement, and PDOException.

A, the PDO

The PDO - > BeginTransaction () - indicates the beginning point of the rollback
The PDO - > Commit () - indicates the end of the rollback and executes the SQL
The PDO - > RollBack () - performs a rollBack
The PDO - > S/s - build an instance of the pdo-linked database
The PDO - > ErrorCode () - gets the errorCode
The PDO - > ErrorInfo () - gets the wrong information
The PDO - > Exec () - processes an SQL statement and returns the number of entries affected
The PDO - > GetAttribute () - gets an attribute of a database connection object
The PDO - > GetAvailableDrivers () - gets the valid PDO driver name
The PDO - > LastInsertId () - gets the primary key value of the last data written
The PDO - > Prepare () - generates a "query object"
The PDO - > Query () - processes an SQL statement and returns a "PDOStatement"
The PDO - > Quote () - adds quotes to a string in SQL
The PDO - > SetAttribute () - sets attributes for a database connection object

1) database connections in PDO
$DSN = 'mysql: dbname = ent; The host = 127.0.0.1 ';
$user = 'root';
$password = '123456');
Try {
$DBH = new PDO($DSN, $user, $password, array(PDO::ATTR_PERSISTENT => True));
The $DBH - > The query (' set names utf8; ');
The foreach ($DBH - > Query ('SELECT * from tpm_juese') as $row) {
Print_r ($row);
}
} catch (PDOException $e) {
Echo 'Connection failed:'. $e-> GetMessage ();
}

Many Web applications are optimized for persistent connections to databases. Persistent connections are not closed at the end of the script,
Instead, it is cached and reused when another script requests a connection using the same identity.
Caching of persistent connections allows you to avoid the resource drain of deploying a new connection every time your script needs to talk to the database, making your Web application faster.
Array (PDO::ATTR_PERSISTENT => True) sets the connection type to a persistent connection.

The $DBH - > BeginTransaction ();
The $DBH - > The exec (" INSERT INTO ` test `. ` table ` (` name `, ` age `) VALUES (' Mick, 22);" );
The $DBH - > The exec (" INSERT INTO ` test `. ` table ` (` name `, ` age `) VALUES (' lily ', 29);" );
The $DBH - > The exec (" INSERT INTO ` test `. ` table ` (` name `, ` age `) VALUES (' Susan ', 21);" );
The $DBH - > Commit ();

} catch (Exception $e) {
The $DBH - > The rollBack ();
Echo "Failed:". $e-> GetMessage ();
}
? >
Now that you have established a connection through PDO, you must understand how PDO manages transactions before deploying queries. If you have never seen the transaction, (now make a brief introduction:) they offer four main features: Atomicity, Consistency, independence and persistence (Atomicity, Consistency, Isolation and Durability, ACID) popular point, all the work you submit a transaction, even if it is performed in stages, and to ensure the safely applied to the database, without the interference by other connection. Transactional work can also be easily canceled automatically if a request goes wrong.

A typical use of a transaction is to "save" a batch of changes and execute them immediately. This will have the benefit of radically improving the efficiency of updates. In other words, transactions can make your scripts faster and possibly more robust (to achieve this you still need to use them correctly).

When the script ends or a connection closes, if you have an unfinished transaction, PDO will automatically roll it back. This is a safe scenario for unexpected script termination - if you do not commit the transaction explicitly, it will assume that something went wrong and execute a rollback for the safety of your data.

Second, the 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 () -- execute a prepared statement
PDOStatement - > Fetch () -- fetch 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

Third, PDOException

PDO provides three different error handling strategies.
1. The PDO: : ERRMODE_SILENT
This is the default mode. PDO sets simple error codes on statement and database objects. You can use PDO-> ErrorCode () and PDO - > The errorInfo() method checks for errors; If the error is caused by a call to a statement object, you can use PDOStatement on that object. ErrorCode () or PDOStatement - > The errorInfo() method gets the error message. If the error is caused by a call to a database object, you should call the two methods on that database object.
2. The PDO: : ERRMODE_WARNING
As an addition to setting the error code, PDO will issue a traditional E_WARNING message. This setting is useful for debugging and debugging if you just want to see what's going on and don't want to break the flow of your program.
3. The PDO: : ERRMODE_EXCEPTION
As an attachment for setting the error code, PDO throws a PDOException exception and sets its properties to reflect the error code and the error message. This setting is also useful when debugging, because it effectively "blows up" the error points in the script, pointing very quickly to an area in your code where errors might occur. Remember: if the exception causes the script to break, the transaction is automatically rolled back.
Exception mode is also useful because you can handle errors with a clearer structure than the traditional php-style error-handling structure, use less code and nesting than in quiet mode, and more explicitly check the return value of each database access.
For more information about Exceptions in PHP, see the Exceptions section
PDO USES an error code string based on sql-92 SQLSTATE. A particular PDO driver should correspond its own code to the appropriate SQLSTATE code. The PDO - > The errorCode() method only returns a single SQLSTATE code. PDO also provides a PDO if you need more specific information about an error. ErrorInfo () method, which returns a string containing the SQLSTATE code, the database-driven error code, and the database-driven error specification.

< ? PHP
// modify the default error display level
The $DBH - > The setAttribute (PDO: : ATTR_ERRMODE, PDO: : ERRMODE_WARNING);
? >

Related articles: