


Detailed explanation of the steps for adding, deleting, modifying and querying mysql database using PDO
This time I will bring you a detailed explanation of the steps for adding, deleting, modifying, and querying operations of PDO on mysql database. What are the precautions for PDO adding, deleting, modifying, and querying operations on mysql database? The following is a practical case. Let’s take a look. .
Preface
PDO is the abbreviation of PHP Data Object. You cannot use the PDO extension itself to perform anydatabase operations, you must use a database-specific PDO driver (PDO driver for a specific database) to access the database server.
PDO does not provide database abstraction. It does not rewrite SQL or provide functions missing from the database itself. If you need this function, you need to use a more mature abstraction layer. Recently I used PDO to operate mysql database when working on a project, so I wrote a class file myself and named it mysql_class.php. The file code is as follows:Sample code
<?php class mysql{ //常量声明 const DSN = "mysql:host=[数据库地址];dbname=[数据库名];charset=utf8";//数据库地址与数据库名及编码 const USERNAME = "[数据库用户名]";//用户名 const PASSWD = "[数据库密码]";//密码 //私有变量声明 private $sql = NULL;//sql语句缓存 private $link = NULL;//数据库连接 private $result = NULL;//结果 /******************************************************************************* * @ 名称:建立连接 * @ 属性:私有 *******************************************************************************/ private function connect(){ try { $this->link = new \PDO(self::DSN, self::USERNAME, self::PASSWD, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));//创建连接 } catch (PDOException $e) { die ("Error!:".$e->getMessage()."<hr/>"); } } /******************************************************************************* * @ 名称:执行sql语句 * @ 属性:私有 * @ 入口参数:无 * @ 出口参数:执行成功返回真,否则返回假,查询语句存储结果集数组 *******************************************************************************/ private function sql(){ try { $this->connect(); $this->link->beginTransaction();//开启一个事务 $prepare = $this->link->prepare($this->sql);//准备查询语句 $prepare->execute();//执行查询语句并返回结果集 $cmd = strtolower(substr(trim($this->sql),0,6));//截取命令字符 if($cmd == "select"){ $array = $prepare->fetch(PDO::FETCH_ASSOC);//获取结果集中的所有数据 if(count($array)){ $this->result = NULL; $this->result = $array;//存储结果集 return true;//查询到结果返回真 }else{ return false;//否则返回假 } }else if($cmd == "insert" || $cmd == "delete" || $cmd == "update"){ if($prepare){ return true;//执行成功返回真 }else{ return false;//否则返回假 } } $this->link->commit(); //如果正确执行完成那么确认commit } catch (PDOException $e) { $this->link->rollBack();//如果执行中有错误的情况下回滚 die ("Error!:".$e->getMessage()."<hr/>"); } } /******************************************************************************* * @ 名称:sql语句处理 * @ 属性:公有 * @ 入口参数:cmd增删改查字符命令;dsname数据表名;first第一个参数;second第二个参数; * @ 出口参数:执行成功返回真,否则返回假,查询操作返回结果集数组 * @ 使用示例: $mysql->handle("insert","abc","openid,nickname","'123','abc'");//增加 $mysql->handle("delete","abc","openid='123'");//删除 $mysql->handle("update","abc","nickname='def'","openid='123'");//更新 $res = $mysql->handle("select","abc","*","openid='123'");//查询 if(is_array($res) == true){ foreach($res as $key=>$val){ echo $key."=".$val."<hr>"; } }//遍历查询结果数组 *******************************************************************************/ public function handle($cmd,$dsname,$first,$second=NULL){ switch($cmd){ case 'insert'://插入 $this->sql = "insert into $dsname ($first) values ($second)"; break; case 'delete'://删除 $this->sql = "delete from $dsname where $first"; break; case 'update'://更新 $this->sql = "update $dsname set $first where $second"; break; case 'select'://查询 $this->sql = "select $first from $dsname where $second"; break; default: die ("Syntax Error!");//提示语法错误 break; } $res = $this->sql();//执行sql语句 if($res){ if($cmd == 'select'){ return $this->result;//返回查询结果 }else{ return true;//执行成功返回真 } }else{ return false;//否则返回假 } $this->link=NULL;;//关闭数据库 } } $mysql = new mysql;//数据库类的实例化 ?>
Detailed explanation of the use of php namespace
Detailed explanation of the use of Laravel 5.5 core architecture
The above is the detailed content of Detailed explanation of the steps for adding, deleting, modifying and querying mysql database using PDO. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

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

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

Undress AI Tool
Undress images for free

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











MySQL and phpMyAdmin are powerful database management tools. 1) MySQL is used to create databases and tables, and to execute DML and SQL queries. 2) phpMyAdmin provides an intuitive interface for database management, table structure management, data operations and user permission management.

Compared with other programming languages, MySQL is mainly used to store and manage data, while other languages such as Python, Java, and C are used for logical processing and application development. MySQL is known for its high performance, scalability and cross-platform support, suitable for data management needs, while other languages have advantages in their respective fields such as data analytics, enterprise applications, and system programming.

Oracle is not only a database company, but also a leader in cloud computing and ERP systems. 1. Oracle provides comprehensive solutions from database to cloud services and ERP systems. 2. OracleCloud challenges AWS and Azure, providing IaaS, PaaS and SaaS services. 3. Oracle's ERP systems such as E-BusinessSuite and FusionApplications help enterprises optimize operations.

In MySQL, the function of foreign keys is to establish the relationship between tables and ensure the consistency and integrity of the data. Foreign keys maintain the effectiveness of data through reference integrity checks and cascading operations. Pay attention to performance optimization and avoid common errors when using them.

The main difference between MySQL and MariaDB is performance, functionality and license: 1. MySQL is developed by Oracle, and MariaDB is its fork. 2. MariaDB may perform better in high load environments. 3.MariaDB provides more storage engines and functions. 4.MySQL adopts a dual license, and MariaDB is completely open source. The existing infrastructure, performance requirements, functional requirements and license costs should be taken into account when choosing.

SQL is a standard language for managing relational databases, while MySQL is a database management system that uses SQL. SQL defines ways to interact with a database, including CRUD operations, while MySQL implements the SQL standard and provides additional features such as stored procedures and triggers.

Redis is a memory data structure storage system, mainly used as a database, cache and message broker. Its core features include single-threaded model, I/O multiplexing, persistence mechanism, replication and clustering functions. Redis is commonly used in practical applications for caching, session storage, and message queues. It can significantly improve its performance by selecting the right data structure, using pipelines and transactions, and monitoring and tuning.

Safely handle functions and regular expressions in JSON In front-end development, JavaScript is often required...
