A simple example of PDO operations in PHP and a simple example of pdo operations. A simple example of PDO operations in PHP. A simple example of pdo operations in this article describes the simple PDO operations in PHP. I would like to share with you the following details: there are a lot of information about PDO on the Internet. This is a simple example of php pdo operations and a simple example of pdo operations.
This article describes the simple PDO operations of PHP. We will share this with you for your reference. The details are as follows:
There is a lot of information about PDO on the Internet. This is not cumbersome.
Here I encapsulate all PDO operations into a class for convenient operations.
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) {$ sqlT Ype = 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 ();}}
Usage:
Include "pdo. php "; $ db = new DB (); $ subjectList = $ db-> query (" SELECT * FROM 'table1 '"); $ count = $ db-> query ("UPDATE 'table1' 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 (transaction supported) MyISAM (transaction not supported) echo $ db-> con-> rollBack (); throw new MyException ("Transaction test error", $ e) ;}$ db = NULL;
PDO supports parameter calls of SQL statements to effectively prevent SQL injection.