


Simple example of PDO operation in PHP, simple example of pdo operation_PHP tutorial
Jul 12, 2016 am 08:55 AMA simple example of PHP's PDO operation, a simple example of pdo operation
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(支持事務(wù)) MyISAM(不支持事務(wù)) echo $db->con->rollBack(); throw new MyException("事務(wù)測試錯誤", $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 of this site: "Summary of PHP Network Programming Skills", "Introduction Tutorial on PHP Basic Grammar", "Summary of PHP Office Document Skills (including word, excel, access, ppt)", "php date and time usage summary", "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.
Articles you may be interested in:
- php uses PDO to operate MySQL database instance
- PHP implements PDO mysql database operation class
- PHP PDO operation summary
- New PDO database operation class php version (only applicable to Mysql)
- Summary of the differences in PDO database operation between PHP 5.1.* and 5.2.*
- A simple way to use PDO in PHP5.2
- A simple way to use PDO in the database abstraction layer in php
- Detailed explanation of the PDO class in PHP
- PDO method to implement database in php Check for additions, deletions, modifications

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

TostaycurrentwithPHPdevelopmentsandbestpractices,followkeynewssourceslikePHP.netandPHPWeekly,engagewithcommunitiesonforumsandconferences,keeptoolingupdatedandgraduallyadoptnewfeatures,andreadorcontributetoopensourceprojects.First,followreliablesource

PHPbecamepopularforwebdevelopmentduetoitseaseoflearning,seamlessintegrationwithHTML,widespreadhostingsupport,andalargeecosystemincludingframeworkslikeLaravelandCMSplatformslikeWordPress.Itexcelsinhandlingformsubmissions,managingusersessions,interacti

TosettherighttimezoneinPHP,usedate_default_timezone_set()functionatthestartofyourscriptwithavalididentifiersuchas'America/New_York'.1.Usedate_default_timezone_set()beforeanydate/timefunctions.2.Alternatively,configurethephp.inifilebysettingdate.timez

TovalidateuserinputinPHP,usebuilt-invalidationfunctionslikefilter_var()andfilter_input(),applyregularexpressionsforcustomformatssuchasusernamesorphonenumbers,checkdatatypesfornumericvalueslikeageorprice,setlengthlimitsandtrimwhitespacetopreventlayout

ThePhpfunctionSerialize () andunserialize () AreusedtoconvertcomplexdaTastructdestoresintostoraSandaBackagain.1.Serialize () c OnvertsdatalikecarraysorobjectsraystringcontainingTypeandstructureinformation.2.unserialize () Reconstruct theoriginalatataprom

You can embed PHP code into HTML files, but make sure that the file has an extension of .php so that the server can parse it correctly. Use standard tags to wrap PHP code, insert dynamic content anywhere in HTML. In addition, you can switch PHP and HTML multiple times in the same file to realize dynamic functions such as conditional rendering. Be sure to pay attention to the server configuration and syntax correctness to avoid problems caused by short labels, quotation mark errors or omitted end labels.

The key to writing clean and easy-to-maintain PHP code lies in clear naming, following standards, reasonable structure, making good use of comments and testability. 1. Use clear variables, functions and class names, such as $userData and calculateTotalPrice(); 2. Follow the PSR-12 standard unified code style; 3. Split the code structure according to responsibilities, and organize it using MVC or Laravel-style catalogs; 4. Avoid noodles-style code and split the logic into small functions with a single responsibility; 5. Add comments at key points and write interface documents to clarify parameters, return values ??and exceptions; 6. Improve testability, adopt dependency injection, reduce global state and static methods. These practices improve code quality, collaboration efficiency and post-maintenance ease.

Yes,youcanrunSQLqueriesusingPHP,andtheprocessinvolveschoosingadatabaseextension,connectingtothedatabase,executingqueriessafely,andclosingconnectionswhendone.Todothis,firstchoosebetweenMySQLiorPDO,withPDObeingmoreflexibleduetosupportingmultipledatabas
