The example in this article describes the simple PDO operation of PHP. Share it with everyone for your reference, the details are as follows:
There is a lot of information about PDO on the Internet. No need to go into details here.
Here I encapsulate all PDO operations into a class for easy operation.
Theclass code is as follows:
class DB { //pdo对象 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 `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 的表类型 InnoDB(支持事务) MyISAM(不支持事务) echo $db->con->rollBack(); throw new MyException("事务测试错误", $e); } $db = NULL;
PDO supports calling SQL statements as parameters, which can effectively prevent SQL injection.
Readers who are interested in more PHP-related content can check out the special topics on this site: "Summary of PHP network programming skills", "Introduction to PHP basic syntax tutorial", "Summary of PHP operating office document skills (including word, excel, access, ppt)", "Summary of PHP date and time usage", "PHP object-oriented programming introductory tutorial》, "php string (string) usage summary", "php mysql database operation introductory tutorial" and "php common database operation skills summary"
I hope this article will be helpful to everyone in PHP programming.