Connector.php
Responsible for communicating with the database, adding, deleting, modifying and reading (CRUD)
First, create a Connector class, and set the attribute
<?php class Connector { // 数据库地址前缀,常见的有mysql,slqlsrv,odbc等等等 private $driver = 'mysql'; // 数据库地址 private $host = 'localhost'; // 数据库默认名称, 设置为静态是因为有切换数据库的需求 private static $db = 'sakila'; // 数据库用户名 private $username = 'root'; // 数据库密码 private $password = ''; // 当前数据库连接 protected $connection; // 数据库连接箱,切换已存在的数据库连接不需要重新通信,从这里取即可 protected static $container = []; // PDO默认属性配置,具体请自行查看文档 protected $options = [ PDO::ATTR_CASE => PDO::CASE_NATURAL, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_ORACLE_NULLS => PDO::NULL_NATURAL, PDO::ATTR_STRINGIFY_FETCHES => false, ]; }
The above code should be understandable with comments , so I won’t explain it further and go directly to the function
-
buildConnectString - is to generate a DSN connection string, very straightforward
protected function buildConnectString() { return "$this->driver:host=$this->host;dbname=".self::$db; } // "mysql:host=localhost;dbname=sakila;"
-
connect - Connect to the database
public function connect() { try { // 连接数据库,生成pdo实例, 将之赋予$connection,并存入$container之中 self::$container[self::$db] = $this->connection = new PDO($this->buildConnectString(), $this->username, $this->password, $this->options); // 返回数据库连接 return $this->connection; } catch (Exception $e) { // 若是失败, 返回原因 // 还记得dd()吗?这个辅助函数还会一直用上 dd($e->getMessage()); } }
-
setDatabase - Switch database
public function setDatabase($db) { self::$db = $db; return $this; }
-
_construct - What is the first step after generating an instance
function construct() { // 如果从未连接过该数据库, 那就新建连接 if(empty(self::$container[self::$db])) $this->connect(); // 反之, 从$container中提取, 无需再次通信 $this->connection = self::$container[self::$db]; }
The next two functional expressions are used together. You may be confused by looking at them alone. Step by step with the exampleDebugging
$a = new Connector(); $bindValues = [ 'PENELOPE', 'GUINESS' ]; dd($a->read('select * from actor where first_name = ? and last_name = ?', $bindValues));
Return value
array (size=1) 0 => object(stdClass)[4] public 'actor_id' => string '1' (length=1) public 'first_name' => string 'PENELOPE' (length=8) public 'last_name' => string 'GUINESS' (length=7) public 'last_update' => string '2006-02-15 04:34:33' (length=19)
-
read - read data
public function read($sql, $bindings) { // 将sql语句放入预处理函数 // $sql = select * from actor where first_name = ? and last_name = ? $statement = $this->connection->prepare($sql); // 将附带参数带入pdo实例 // $bindings = ['PENELOPE', 'GUINESS'] $this->bindValues($statement, $bindings); // 执行 $statement->execute(); // 返回所有合法数据, 以Object对象为数据类型 return $statement->fetchAll(PDO::FETCH_OBJ); }
-
bindValues - bring the attached parameters into the pdo instance
// 从例子中可以看出, 我用在预处理的变量为?, 这是因为pdo的局限性, 有兴趣可以在评论区讨论这个问题 public function bindValues($statement, $bindings) { // $bindings = ['PENELOPE', 'GUINESS'] // 依次循环每一个参数 foreach ($bindings as $key => $value) { // $key = 0/1 // $value = 'PENELOPE'/'GUINESS' $statement->bindValue( // 如果是字符串类型, 那就直接使用, 反之是数字, 将其+1 // 这里是数值, 因此返回1/2 is_string($key) ? $key : $key + 1, // 直接放入值 // 'PENELOPE'/'GUINESS' $value, // 这里直白不多说 // PDO::PARAM_STR/PDO::PARAM_STR is_int($value) ? PDO::PARAM_INT : PDO::PARAM_STR ); } }
So do you understand _( :3 ∠)
- #update - Rewrite data
// 与read不同的地方在于, read返回数据, update返回boolean(true/false) public function update($sql, $bindings) { $statement = $this->connection->prepare($sql); $this->bindValues($statement, $bindings); return $statement->execute(); }
-
// 与update一样, 分开是因为方便日后维护制定 public function delete($sql, $bindings) { $statement = $this->connection->prepare($sql); $this->bindValues($statement, $bindings); return $statement->execute(); }
- create - Add data
// 返回最新的自增ID, 如果有 public function create($sql, $bindings) { $statement = $this->connection->prepare($sql); $this->bindValues($statement, $bindings); $statement->execute(); return $this->lastInsertId(); }
- lastInsertId - Return
Add id, if any
// pdo自带,只是稍微封装 public function lastInsertId() { $id = $this->connection->lastInsertId(); return empty($id) ? null : $id; }
- ##exec - Suitable for additions, deletions and modifications
-
public function exec($sql) { return $this->connection->exec($sql); }
query - Suitable for reading -
public function query($sql) { $q = $this->connection->query($sql); return $q->fetchAll(PDO::FETCH_OBJ); }
Encapsulates functions related to database transactions, straightforward so there are no comments
public function beginTransaction() { $this->connection->beginTransaction(); return $this; } public function rollBack() { $this->connection->rollBack(); return $this; } public function commit() { $this->connection->commit(); return $this; } public function inTransaction() { return $this->connection->inTransaction(); }
Complete code
<?php class Connector { // 数据库地址前缀,常见的有mysql,slqlsrv,odbc等等等 private $driver = 'mysql'; // 数据库地址 private $host = 'localhost'; // 数据库默认名称, 设置为静态是因为有切换数据库的需求 private static $db = 'sakila'; // 数据库用户名 private $username = 'root'; // 数据库密码 private $password = ''; // 当前数据库连接 protected $connection; // 数据库连接箱,切换已存在的数据库连接不需要重新通信,从这里取即可 protected static $container = []; // PDO默认属性配置,具体请自行查看文档 protected $options = [ PDO::ATTR_CASE => PDO::CASE_NATURAL, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_ORACLE_NULLS => PDO::NULL_NATURAL, PDO::ATTR_STRINGIFY_FETCHES => false, ]; function construct() { // 如果从未连接过该数据库, 那就新建连接 if(empty(self::$container[self::$db])) $this->connect(); // 反之, 从$container中提取, 无需再次通信 $this->connection = self::$container[self::$db]; } // 生成DSN连接串 protected function buildConnectString() { return "$this->driver:host=$this->host;dbname=".self::$db; } // 连接数据库 public function connect() { try { // 连接数据库,生成pdo实例, 将之赋予$connection,并存入$container之中 self::$container[self::$db] = $this->connection = new PDO($this->buildConnectString(), $this->username, $this->password, $this->options); // 返回数据库连接 return $this->connection; } catch (Exception $e) { // 若是失败, 返回原因 dd($e->getMessage()); } } // 切换数据库 public function setDatabase($db) { self::$db = $db; return $this; } // 读取数据 public function read($sql, $bindings) { // 将sql语句放入预处理函数 $statement = $this->connection->prepare($sql); // 将附带参数带入pdo实例 $this->bindValues($statement, $bindings); // 执行 $statement->execute(); // 返回所有合法数据, 以Object对象为数据类型 return $statement->fetchAll(PDO::FETCH_OBJ); } // 将附带参数带入pdo实例 public function bindValues($statement, $bindings) { // 依次循环每一个参数 foreach ($bindings as $key => $value) { $statement->bindValue( // 如果是字符串类型, 那就直接使用, 反之是数字, 将其+1 is_string($key) ? $key : $key + 1, // 直接放入值 $value, // 这里直白不多说 is_int($value) ? PDO::PARAM_INT : PDO::PARAM_STR ); } } // 改写数据 public function update($sql, $bindings) { // 与read不同的地方在于, read返回数据, update返回boolean(true/false) $statement = $this->connection->prepare($sql); $this->bindValues($statement, $bindings); return $statement->execute(); } // 删除数据 public function delete($sql, $bindings) { $statement = $this->connection->prepare($sql); $this->bindValues($statement, $bindings); return $statement->execute(); } // 增加数据 public function create($sql, $bindings) { $statement = $this->connection->prepare($sql); $this->bindValues($statement, $bindings); $statement->execute(); return $this->lastInsertId(); } // 返回新增id, 如果有 public function lastInsertId() { $id = $this->connection->lastInsertId(); return empty($id) ? null : $id; } // 适用于增删改 public function exec($sql) { return $this->connection->exec($sql); } // 适用于读 public function query($sql) { $q = $this->connection->query($sql); return $q->fetchAll(PDO::FETCH_OBJ); } public function beginTransaction() { $this->connection->beginTransaction(); return $this; } public function rollBack() { $this->connection->rollBack(); return $this; } public function commit() { $this->connection->commit(); return $this; } public function inTransaction() { return $this->connection->inTransaction(); } }
Questions in this issue
1.) Due to the characteristics of PHP itself, by default all code classes will be destructed after running, and pdo will automatically break connection, so I did not disconnect() and let pdo disconnect. I wonder if this is a bad practice?
2.) The two functions of adding and rewriting data do not support adding multiple sets of data at one time. This is a one-time addition. The reason is that I deleted it because I thought it was too cumbersome. If you are interested, you can provide a solutionThe above is the detailed content of How to write your own database package (2). For more information, please follow other related articles on the PHP Chinese website!

Stored procedures are precompiled SQL statements in MySQL for improving performance and simplifying complex operations. 1. Improve performance: After the first compilation, subsequent calls do not need to be recompiled. 2. Improve security: Restrict data table access through permission control. 3. Simplify complex operations: combine multiple SQL statements to simplify application layer logic.

The working principle of MySQL query cache is to store the results of SELECT query, and when the same query is executed again, the cached results are directly returned. 1) Query cache improves database reading performance and finds cached results through hash values. 2) Simple configuration, set query_cache_type and query_cache_size in MySQL configuration file. 3) Use the SQL_NO_CACHE keyword to disable the cache of specific queries. 4) In high-frequency update environments, query cache may cause performance bottlenecks and needs to be optimized for use through monitoring and adjustment of parameters.

The reasons why MySQL is widely used in various projects include: 1. High performance and scalability, supporting multiple storage engines; 2. Easy to use and maintain, simple configuration and rich tools; 3. Rich ecosystem, attracting a large number of community and third-party tool support; 4. Cross-platform support, suitable for multiple operating systems.

The steps for upgrading MySQL database include: 1. Backup the database, 2. Stop the current MySQL service, 3. Install the new version of MySQL, 4. Start the new version of MySQL service, 5. Recover the database. Compatibility issues are required during the upgrade process, and advanced tools such as PerconaToolkit can be used for testing and optimization.

MySQL backup policies include logical backup, physical backup, incremental backup, replication-based backup, and cloud backup. 1. Logical backup uses mysqldump to export database structure and data, which is suitable for small databases and version migrations. 2. Physical backups are fast and comprehensive by copying data files, but require database consistency. 3. Incremental backup uses binary logging to record changes, which is suitable for large databases. 4. Replication-based backup reduces the impact on the production system by backing up from the server. 5. Cloud backups such as AmazonRDS provide automation solutions, but costs and control need to be considered. When selecting a policy, database size, downtime tolerance, recovery time, and recovery point goals should be considered.

MySQLclusteringenhancesdatabaserobustnessandscalabilitybydistributingdataacrossmultiplenodes.ItusestheNDBenginefordatareplicationandfaulttolerance,ensuringhighavailability.Setupinvolvesconfiguringmanagement,data,andSQLnodes,withcarefulmonitoringandpe

Optimizing database schema design in MySQL can improve performance through the following steps: 1. Index optimization: Create indexes on common query columns, balancing the overhead of query and inserting updates. 2. Table structure optimization: Reduce data redundancy through normalization or anti-normalization and improve access efficiency. 3. Data type selection: Use appropriate data types, such as INT instead of VARCHAR, to reduce storage space. 4. Partitioning and sub-table: For large data volumes, use partitioning and sub-table to disperse data to improve query and maintenance efficiency.

TooptimizeMySQLperformance,followthesesteps:1)Implementproperindexingtospeedupqueries,2)UseEXPLAINtoanalyzeandoptimizequeryperformance,3)Adjustserverconfigurationsettingslikeinnodb_buffer_pool_sizeandmax_connections,4)Usepartitioningforlargetablestoi


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

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 English version
Recommended: Win version, supports code prompts!

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.
