The PHP Data Object (PDO) extension defines a lightweight, consistent interface for the PHP Access database.
PDO provides a data access abstraction layer, which means that the same functions (methods) can be used to query and fetch data regardless of the database used.
PDO is released with PHP5.1 and can be used in the PHP5.0 pecl extension and cannot be run in previous versions of PHP.
This article mainly introduces the operation of the PDO in PHP, with a simple example to analyze the simple connection of the PHP operation PDO, initialization and query, insertion and other operational skills, the need for friends can refer to, here I will all the PDO operation package into a class convenient operation.
The class code is as follows:
Class DB { //pdo object public $con = NULL; function DB () { $this->con = new PDO ("Mysql:host=127.0.0.1;dbname=dbtest", "root", "xxx", Array ( PDO:: Mysql_attr_init_command = ' SET NAMES ' UTF8 ', pdo::attr_persistent = TRUE, )); $this->con->setattribute (Pdo::attr_errmode, pdo::errmode_exception); $this->con->setattribute (Pdo::attr_case, pdo::case_upper); } Public Function query ($sql, $para = NULL) { $sqlType = Strtoupper (substr ($sql, 0, 6)); $cmd = $this->con->prepare ($sql); if ($para! = NULL) { $cmd->execute ($para); } else { $cmd->execute (); } if ($sqlType = = "Select") { return $cmd->fetchall (); } if ($sqlType = = "INSERT") { return $this->con->lastinsertid (); } return $cmd->rowcount ();} }
How to use:
Include "pdo.php", $db = new db (), $subjectList = $db->query ("select * from ' table1 '"), $count = $db->query ("UPDATE" ta Ble1 ' SET ' name ' = ' Test ' WHERE ' id ' =: id ', array (': id ' = ' 795 '); try{ echo $db->con->begintransaction ();
$count = $db->con->exec ("UPDATE ' table1 ' SET ' name ' = ' test1 ' WHERE ' id ' = 795"); $count = $db->con->exec ("UPDATE ' table1 ' SET ' name1 ' = ' test22 ' WHERE ' id ' = 795 '); $count = $db->con->exec ("UPDATE ' table1 ' SET ' name1 ' = ' test333 ' WHERE ' id ' = 795 '); echo $db->con->commit ();} catch (Exception $e) { //MYSQL table type InnoDB (Support transaction) MyISAM (transaction not supported) echo $db->con->rollback (); throw new MyException ("Transaction test Error", $e);} $db = NULL;
PDO supports SQL statements to be invoked as arguments, effectively preventing SQL injection.