这篇文章主要介绍了php封装的数据库函数与用法,基于thinkPHP中数据库操作相关代码整理简化而来,包括针对数据库的设置、连接、查询及日志操作等功能,简单实用,需要的朋友可以参考下
本文实例讲述了php封装的数据库函数与用法。分享给大家供大家参考,具体如下:
从Thinkphp里面抽离出来的数据库模块,感觉挺好用
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; ?>
数据库模型类Model.class.php,放到classes/目录下:
<?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(); } }
例子:
#include "common.php" function test(){ $model = M(); $sql = "select * from test"; $list = $model->query($sql); _dump($list); }
以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!
相关推荐:
以上是php封装的数据库函数与用法的详细内容。更多信息请关注PHP中文网其他相关文章!

在PHP中,可以使用session_status()或session_id()来检查会话是否已启动。1)使用session_status()函数,如果返回PHP_SESSION_ACTIVE,则会话已启动。2)使用session_id()函数,如果返回非空字符串,则会话已启动。这两种方法都能有效地检查会话状态,选择使用哪种方法取决于PHP版本和个人偏好。

sessionsarevitalinwebapplications,尤其是在commercePlatform之前。

在PHP中管理并发会话访问可以通过以下方法:1.使用数据库存储会话数据,2.采用Redis或Memcached,3.实施会话锁定策略。这些方法有助于确保数据一致性和提高并发性能。

PHPsessionshaveseverallimitations:1)Storageconstraintscanleadtoperformanceissues;2)Securityvulnerabilitieslikesessionfixationattacksexist;3)Scalabilityischallengingduetoserver-specificstorage;4)Sessionexpirationmanagementcanbeproblematic;5)Datapersis

负载均衡会影响会话管理,但可以通过会话复制、会话粘性和集中式会话存储解决。1.会话复制在服务器间复制会话数据。2.会话粘性将用户请求定向到同一服务器。3.集中式会话存储使用独立服务器如Redis存储会话数据,确保数据共享。

Sessionlockingisatechniqueusedtoensureauser'ssessionremainsexclusivetooneuseratatime.Itiscrucialforpreventingdatacorruptionandsecuritybreachesinmulti-userapplications.Sessionlockingisimplementedusingserver-sidelockingmechanisms,suchasReentrantLockinJ

PHP会话的替代方案包括Cookies、Token-basedAuthentication、Database-basedSessions和Redis/Memcached。1.Cookies通过在客户端存储数据来管理会话,简单但安全性低。2.Token-basedAuthentication使用令牌验证用户,安全性高但需额外逻辑。3.Database-basedSessions将数据存储在数据库中,扩展性好但可能影响性能。4.Redis/Memcached使用分布式缓存提高性能和扩展性,但需额外配

Sessionhijacking是指攻击者通过获取用户的sessionID来冒充用户。防范方法包括:1)使用HTTPS加密通信;2)验证sessionID的来源;3)使用安全的sessionID生成算法;4)定期更新sessionID。


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

DVWA
Damn Vulnerable Web App (DVWA) 是一个PHP/MySQL的Web应用程序,非常容易受到攻击。它的主要目标是成为安全专业人员在合法环境中测试自己的技能和工具的辅助工具,帮助Web开发人员更好地理解保护Web应用程序的过程,并帮助教师/学生在课堂环境中教授/学习Web应用程序安全。DVWA的目标是通过简单直接的界面练习一些最常见的Web漏洞,难度各不相同。请注意,该软件中

禅工作室 13.0.1
功能强大的PHP集成开发环境

螳螂BT
Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。

ZendStudio 13.5.1 Mac
功能强大的PHP集成开发环境