PDO ---- Data Access abstraction layer, pdo ---- Abstraction Layer
I. Functions
1. access other databases
2. Have transaction Functions
3. Pre-processing statement function (preventing SQL injection attacks)
Ii. Method
1. Create a PDO object
$ Dsn = "mysql: dbname = mydb; host = localhost ";
$ Pdo = newpdo ($ dsn, "root", "123 ");
2. Write SQL statements
$ SQL = "select * from nation ";
$ SQL = "insert into nation values ('n087 ',' is ')";
3. Execute SQL statements
$ Stm = $ pdo-> query ($ SQL );
$ Arr = $ pdo-> exec ($ SQL );
4. read data from the PDOStatement object
$ Arr = $ stm-> fetchAll (PDO: FETCH_NUM );
Var_dump ($ arr );
Iii. Transactions
1. Process
(1) beginTransaction start the transaction
(2) commit a transaction with commit
(3) rollback
2. Method
(1) create a PDO object
$ Dsn = "mysql: dbname = mydb; host = localhost ";
$ Pdo = newpdo ($ dsn, "root", "123 ");
(2) set the Error Type of PDO to the exception mode.
$pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
try
{
(3) Start a transaction
$ Pdo-> beginTransaction ();
$ Sql1 = "insert into nation values ('082 ', 'data ')";
$ Sql2 = "insert into nation values ('084 ', 'database ')";
$ Sql3 = "insert into nation values ('083 ', 'handsome guy ')";
$ Pdo-> exec ($ sql1 );
$ Pdo-> exec ($ sql2 );
$ Pdo-> exec ($ sql3 );
(4) commit a transaction
$ Pdo-> commit ();
}
Catch (Exception $ e)
{
(5) rollback
$ Pdo-> rollBack ();
}
Final
{
The code will be executed no matter whether an exception occurs.
}