PHP encapsulated database functions and usage
This article mainly introduces the database functions and usage of PHP encapsulation. It is based on the simplified database operation related code in thinkPHP, including functions such as database settings, connections, queries and log operations. It is simple and practical, and friends in need You can refer to the following
The examples in this article describe the database functions and usage of PHP encapsulation. Share it with everyone for your reference, the details are as follows:
The database module extracted from Thinkphp, I feel it is very easy to use
common.php:
<?PHP /** * 通用函数 */ //包含配置文件 if (is_file("config.php")) { C(include 'config.php'); } if (!function_exists("__autoload")) { function __autoload($class_name) { require_once('classes/' . $class_name . '.class.php'); } } /** * 数据库操作函数 * @return \mysqli */ function M() { $db = new Model(); if (mysqli_connect_errno()) throw_exception(mysqli_connect_error()); return $db; } // 获取配置值 function C($name = null, $value = null) { //静态全局变量,后面的使用取值都是在 $)config数组取 static $_config = array(); // 无参数时获取所有 if (empty($name)) return $_config; // 优先执行设置获取或赋值 if (is_string($name)) { if (!strpos($name, '.')) { $name = strtolower($name); if (is_null($value)) return isset($_config[$name]) ? $_config[$name] : null; $_config[$name] = $value; return; } // 二维数组设置和获取支持 $name = explode('.', $name); $name[0] = strtolower($name[0]); if (is_null($value)) return isset($_config[$name[0]][$name[1]]) ? $_config[$name[0]][$name[1]] : null; $_config[$name[0]][$name[1]] = $value; return; } // 批量设置 if (is_array($name)) { return $_config = array_merge($_config, array_change_key_case($name)); } return null; // 避免非法参数 } function ajaxReturn($data = null, $message = "", $status) { $ret = array(); $ret["data"] = $data; $ret["message"] = $message; $ret["status"] = $status; echo json_encode($ret); die(); } //调试数组 function _dump($var) { if (C("debug")) dump($var); } // 浏览器友好的变量输出 function dump($var, $echo = true, $label = null, $strict = true) { $label = ($label === null) ? '' : rtrim($label) . ' '; if (!$strict) { if (ini_get('html_errors')) { $output = print_r($var, true); $output = '<pre class="brush:php;toolbar:false">' . $label . htmlspecialchars($output, ENT_QUOTES) . ''; } else { $output = $label . print_r($var, true); } } else { ob_start(); var_dump($var); $output = ob_get_clean(); if (!extension_loaded('xdebug')) { $output = preg_replace("/\]\=\>\n(\s+)/m", '] => ', $output); $output = '
' . $label . htmlspecialchars($output, ENT_QUOTES) . ''; } } if ($echo) { echo($output); return null; } else return $output; } /** * 调试输出 * @param type $msg */ function _debug($msg) { if (C("debug")) echo "$msg
"; } function _log($filename, $msg) { $time = date("Y-m-d H:i:s"); $msg = "[$time]\n$msg\r\n"; if (C("log")) { $fd = fopen($filename, "a+"); fwrite($fd, $msg); fclose($fd); } } /** * 日志记录 * @param type $str */ function L($msg) { $time = date("Y-m-d H:i:s"); $clientIP = $_SERVER['REMOTE_ADDR']; $msg = "[$time $clientIP] $msg\r\n"; $log_file = C("LOGFILE"); _log($log_file, $msg); } ?>
config.php:
<?php /** * 数据库配置文件 */ $db = array( 'DB_TYPE' => 'mysql', 'DB_HOST' => '127.0.0.1', 'DB_NAME' => 'DB', 'DB_USER' => 'USER', 'DB_PWD' => 'PWD', 'DB_PORT' => '3306', ); return $db; ?>
Database model class Model.class.php, put it in the classes/ directory:
<?php /** * 数据库模型类 */ class Model { // 数据库连接ID 支持多个连接 protected $linkID = array(); // 当前数据库操作对象 protected $db = null; // 当前查询ID protected $queryID = null; // 当前SQL指令 protected $queryStr = ''; // 是否已经连接数据库 protected $connected = false; // 返回或者影响记录数 protected $numRows = 0; // 返回字段数 protected $numCols = 0; // 最近错误信息 protected $error = ''; public function __construct() { $this->db = $this->connect(); } /** * 连接数据库方法 */ public function connect($config = '', $linkNum = 0) { if (!isset($this->linkID[$linkNum])) { if (empty($config)) $config = array( 'username' => C('DB_USER'), 'password' => C('DB_PWD'), 'hostname' => C('DB_HOST'), 'hostport' => C('DB_PORT'), 'database' => C('DB_NAME') ); $this->linkID[$linkNum] = new mysqli($config['hostname'], $config['username'], $config['password'], $config['database'], $config['hostport'] ? intval($config['hostport']) : 3306); if (mysqli_connect_errno()) throw_exception(mysqli_connect_error()); $this->connected = true; } return $this->linkID[$linkNum]; } /** * 初始化数据库连接 */ protected function initConnect() { if (!$this->connected) { $this->db = $this->connect(); } } /** * 获得所有的查询数据 * @access private * @param string $sql sql语句 * @return array */ public function select($sql) { $this->initConnect(); if (!$this->db) return false; $query = $this->db->query($sql); $list = array(); if (!$query) return $list; while ($rows = $query->fetch_assoc()) { $list[] = $rows; } return $list; } /** * 只查询一条数据 */ public function find($sql) { $resultSet = $this->select($sql); if (false === $resultSet) { return false; } if (empty($resultSet)) {// 查询结果为空 return null; } $data = $resultSet[0]; return $data; } /** * 获取一条记录的某个字段值 , sql 由自己组织 * 例子: $model->getField("select id from user limit 1") */ public function getField($sql) { $resultSet = $this->select($sql); if (!empty($resultSet)) { return reset($resultSet[0]); } } /** * 执行查询 返回数据集 */ public function query($str) { $this->initConnect(); if (!$this->db) { if (C("debug")) echo "connect to database error"; return false; } $this->queryStr = $str; //释放前次的查询结果 if ($this->queryID) $this->free(); $this->queryID = $this->db->query($str); // 对存储过程改进 if ($this->db->more_results()) { while (($res = $this->db->next_result()) != NULL) { $res->free_result(); } } //$this->debug(); if (false === $this->queryID) { echo $this->error(); return false; } else { $this->numRows = $this->queryID->num_rows; $this->numCols = $this->queryID->field_count; return $this->getAll(); } } /** * 执行语句 , 例如插入,更新操作 * @access public * @param string $str sql指令 * @return integer */ public function execute($str) { $this->initConnect(); if (!$this->db) return false; $this->queryStr = $str; //释放前次的查询结果 if ($this->queryID) $this->free(); $result = $this->db->query($str); if (false === $result) { $this->error(); return false; } else { $this->numRows = $this->db->affected_rows; $this->lastInsID = $this->db->insert_id; return $this->numRows; } } /** * 获得所有的查询数据 * @access private * @param string $sql sql语句 * @return array */ private function getAll() { //返回数据集 $result = array(); if ($this->numRows > 0) { //返回数据集 for ($i = 0; $i < $this->numRows; $i++) { $result[$i] = $this->queryID->fetch_assoc(); } $this->queryID->data_seek(0); } return $result; } /** * 返回最后插入的ID */ public function getLastInsID() { return $this->db->insert_id; } // 返回最后执行的sql语句 public function _sql() { return $this->queryStr; } /** * 数据库错误信息 */ public function error() { $this->error = $this->db->errno . ':' . $this->db->error; if ('' != $this->queryStr) { $this->error .= "\n [ SQL语句 ] : " . $this->queryStr; } //trace($this->error, '', 'ERR'); return $this->error; } /** * 释放查询结果 */ public function free() { $this->queryID->free_result(); $this->queryID = null; } /** * 关闭数据库 */ public function close() { if ($this->db) { $this->db->close(); } $this->db = null; } /** * 析构方法 */ public function __destruct() { if ($this->queryID) { $this->free(); } // 关闭连接 $this->close(); } }
Example:
#include "common.php" function test(){ $model = M(); $sql = "select * from test"; $list = $model->query($sql); _dump($list); }
The above is the entire content of this article , I hope it will be helpful to everyone’s learning. For more related content, please pay attention to the PHP Chinese website!
Related recommendations:
thinkPHP5.0 framework method of accessing URL
thinkPHP5.0 framework configuration format, loading parsing and reading Methods
The above is the detailed content of PHP encapsulated database functions and usage. 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

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

MySQL is an open source relational database management system. 1) Create database and tables: Use the CREATEDATABASE and CREATETABLE commands. 2) Basic operations: INSERT, UPDATE, DELETE and SELECT. 3) Advanced operations: JOIN, subquery and transaction processing. 4) Debugging skills: Check syntax, data type and permissions. 5) Optimization suggestions: Use indexes, avoid SELECT* and use transactions.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

In PHP8, match expressions are a new control structure that returns different results based on the value of the expression. 1) It is similar to a switch statement, but returns a value instead of an execution statement block. 2) The match expression is strictly compared (===), which improves security. 3) It avoids possible break omissions in switch statements and enhances the simplicity and readability of the code.

ThinkPHP6 routing parameters are processed in Chinese and complete acquisition. In the ThinkPHP6 framework, URL parameters containing special characters (such as Chinese and punctuation marks) are often processed...
