>  기사  >  백엔드 개발  >  PHP로 캡슐화된 데이터베이스 기능 및 사용법

PHP로 캡슐화된 데이터베이스 기능 및 사용법

不言
不言원래의
2018-06-08 10:04:471754검색

이 글은 주로 데이터베이스 설정, 연결, 쿼리, 로그 작업 등의 기능을 포함하여 thinkPHP의 데이터베이스 작업 관련 코드를 기반으로 PHP 캡슐화의 데이터베이스 기능과 사용법을 소개합니다. 필요한 사람은 참조할 수 있습니다. 다음

이 문서의 예에서는 PHP 캡슐화의 데이터베이스 기능과 사용법을 설명합니다. 참조를 위해 모든 사람과 공유하세요. 세부 사항은 다음과 같습니다.

Thinkphp에서 추출한 데이터베이스 모듈은 사용하기 매우 쉽습니다

common.php:

<?PHP
/**
 * 通用函数
 */
//包含配置文件
if (is_file("config.php")) {
 C(include &#39;config.php&#39;);
}
if (!function_exists("__autoload")) {
 function __autoload($class_name) {
  require_once(&#39;classes/&#39; . $class_name . &#39;.class.php&#39;);
 }
}
/**
 * 数据库操作函数
 * @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, &#39;.&#39;)) {
   $name = strtolower($name);
   if (is_null($value))
    return isset($_config[$name]) ? $_config[$name] : null;
   $_config[$name] = $value;
   return;
  }
  // 二维数组设置和获取支持
  $name = explode(&#39;.&#39;, $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) ? &#39;&#39; : rtrim($label) . &#39; &#39;;
 if (!$strict) {
  if (ini_get(&#39;html_errors&#39;)) {
   $output = print_r($var, true);
   $output = &#39;<pre class="brush:php;toolbar:false">&#39; . $label . htmlspecialchars($output, ENT_QUOTES) . &#39;
'; } 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 = '
&#39; . $label . htmlspecialchars($output, ENT_QUOTES) . &#39;
'; } } 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(
 &#39;DB_TYPE&#39; => &#39;mysql&#39;,
 &#39;DB_HOST&#39; => &#39;127.0.0.1&#39;,
 &#39;DB_NAME&#39; => &#39;DB&#39;,
 &#39;DB_USER&#39; => &#39;USER&#39;,
 &#39;DB_PWD&#39; => &#39;PWD&#39;,
 &#39;DB_PORT&#39; => &#39;3306&#39;,
);
return $db;
?>

데이터베이스 모델 클래스 Model.class.php, 클래스/ 디렉토리에 넣습니다:

<?php
/**
 * 数据库模型类
 */
class Model {
 // 数据库连接ID 支持多个连接
 protected $linkID = array();
 // 当前数据库操作对象
 protected $db = null;
 // 当前查询ID
 protected $queryID = null;
 // 当前SQL指令
 protected $queryStr = &#39;&#39;;
 // 是否已经连接数据库
 protected $connected = false;
 // 返回或者影响记录数
 protected $numRows = 0;
 // 返回字段数
 protected $numCols = 0;
 // 最近错误信息
 protected $error = &#39;&#39;;
 public function __construct() {
  $this->db = $this->connect();
 }
 /**
  * 连接数据库方法
  */
 public function connect($config = &#39;&#39;, $linkNum = 0) {
  if (!isset($this->linkID[$linkNum])) {
   if (empty($config))
    $config = array(
     &#39;username&#39; => C(&#39;DB_USER&#39;),
     &#39;password&#39; => C(&#39;DB_PWD&#39;),
     &#39;hostname&#39; => C(&#39;DB_HOST&#39;),
     &#39;hostport&#39; => C(&#39;DB_PORT&#39;),
     &#39;database&#39; => C(&#39;DB_NAME&#39;)
    );
   $this->linkID[$linkNum] = new mysqli($config[&#39;hostname&#39;], $config[&#39;username&#39;], $config[&#39;password&#39;], $config[&#39;database&#39;], $config[&#39;hostport&#39;] ? intval($config[&#39;hostport&#39;]) : 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 . &#39;:&#39; . $this->db->error;
  if (&#39;&#39; != $this->queryStr) {
   $this->error .= "\n [ SQL语句 ] : " . $this->queryStr;
  }
  //trace($this->error, &#39;&#39;, &#39;ERR&#39;);
  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 중국어 홈페이지를 주목해주세요!

관련 권장사항:

ThinkPHP5.0 프레임워크 URL 액세스 방법

thinkPHP5.0 프레임워크 구성 형식, 로드, 구문 분석 및 읽기 방법

위 내용은 PHP로 캡슐화된 데이터베이스 기능 및 사용법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.