国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

首頁 后端開發(fā) php教程 php pdo數(shù)據(jù)庫操作封裝類代碼

php pdo數(shù)據(jù)庫操作封裝類代碼

Jul 25, 2016 am 08:51 AM

  1. /**

  2.  * 數(shù)據(jù)庫PDO操作
  3.  */
  4. class MysqlPdo {
  5. public static $PDOStatement = null;
  6. /**
  7. * 數(shù)據(jù)庫的連接參數(shù)配置
  8. * @var array
  9. * @access public
  10. */
  11. public static $config = array();
  12. /**
  13. * 是否使用永久連接
  14. * @var bool
  15. * @access public
  16. */
  17. public static $pconnect = false;
  18. /**
  19. * 錯誤信息
  20. * @var string
  21. * @access public
  22. */
  23. public static $error = '';
  24. /**
  25. * 單件模式,保存Pdo類唯一實例,數(shù)據(jù)庫的連接資源
  26. * @var object
  27. * @access public
  28. */
  29. protected static $link;
  30. /**
  31. * 是否已經(jīng)連接數(shù)據(jù)庫
  32. * @var bool
  33. * @access public
  34. */
  35. public static $connected = false;
  36. /**
  37. * 數(shù)據(jù)庫版本
  38. * @var string
  39. * @access public
  40. */
  41. public static $dbVersion = null;
  42. /**
  43. * 當(dāng)前SQL語句
  44. * @var string
  45. * @access public
  46. */
  47. public static $queryStr = '';
  48. /**
  49. * 最后插入記錄的ID
  50. * @var integer
  51. * @access public
  52. */
  53. public static $lastInsertId = null;
  54. /**
  55. * 返回影響記錄數(shù)
  56. * @var integer
  57. * @access public
  58. */
  59. public static $numRows = 0;
  60. // 事務(wù)指令數(shù)
  61. public static $transTimes = 0;
  62. /**
  63. * 構(gòu)造函數(shù),
  64. * @param $dbconfig 數(shù)據(jù)庫連接相關(guān)信息,array('ServerName', 'UserName', 'Password', 'DefaultDb', 'DB_Port', 'DB_TYPE')
  65. */
  66. public function __construct($dbConfig=''){
  67. if (!class_exists('PDO')) self::throw_exception("不支持:PDO");
  68. //若沒有傳輸任何參數(shù),則使用默認(rèn)的數(shù)據(jù)定義
  69. if (!is_array($dbConfig)) {
  70. $dbConfig = array(
  71. 'hostname' => DB_HOST,
  72. 'username' => DB_USER,
  73. 'password' => DB_PWD,
  74. 'database' => DB_NAME,
  75. 'hostport' => DB_PORT,
  76. 'dbms' => DB_TYPE,
  77. 'dsn' => DB_TYPE.":host=".DB_HOST.";dbname=".DB_NAME
  78. );
  79. }
  80. if(empty($dbConfig['hostname'])) self::throw_exception("沒有定義數(shù)據(jù)庫配置");
  81. self::$config = $dbConfig;
  82. if(empty(self::$config['params'])) self::$config['params'] = array();
  83. /*************************************華麗分隔線*******************************************/
  84. if (!isset(self::$link) ) {
  85. $configs = self::$config;
  86. if(self::$pconnect) {
  87. $configs['params'][constant('PDO::ATTR_PERSISTENT')] = true;
  88. }
  89. try {
  90. self::$link = new PDO( $configs['dsn'], $configs['username'], $configs['password'],$configs['params']);
  91. } catch (PDOException $e) {
  92. self::throw_exception($e->getMessage());
  93. }
  94. if(!self::$link) {
  95. self::throw_exception('PDO CONNECT ERROR');
  96. return false;
  97. }
  98. self::$link->exec('SET NAMES '.DB_CHARSET);
  99. self::$dbVersion = self::$link->getAttribute(constant("PDO::ATTR_SERVER_INFO"));
  100. // 標(biāo)記連接成功
  101. self::$connected = true;
  102. // 注銷數(shù)據(jù)庫連接配置信息
  103. unset($configs);
  104. }
  105. return self::$link;
  106. }
  107. /**
  108. * 釋放查詢結(jié)果
  109. * @access function
  110. */
  111. static function free() {
  112. self::$PDOStatement = null;
  113. }
  114. /************************/
  115. /* 數(shù)據(jù)庫操作 */
  116. /************************/
  117. /**
  118. * 獲得所有的查詢數(shù)據(jù)
  119. * @access function
  120. * @return array
  121. */
  122. static function getAll($sql=null) {
  123. if($sql != null)
  124. {
  125. self::query($sql);
  126. }
  127. //返回數(shù)據(jù)集
  128. $result = self::$PDOStatement->fetchAll(constant('PDO::FETCH_ASSOC'));
  129. return $result;
  130. }
  131. /**
  132. * 獲得一條查詢結(jié)果
  133. * @access function
  134. * @param string $sql SQL指令
  135. * @param integer $seek 指針位置
  136. * @return array
  137. */
  138. static function getRow($sql=null) {
  139. if($sql != null)
  140. {
  141. self::query($sql);
  142. }
  143. // 返回數(shù)組集
  144. $result = self::$PDOStatement->fetch(constant('PDO::FETCH_ASSOC'),constant('PDO::FETCH_ORI_NEXT'));
  145. return $result;
  146. }
  147. /**
  148. * 執(zhí)行sql語句,自動判斷進(jìn)行查詢或者執(zhí)行操作
  149. * @access function
  150. * @param string $sql SQL指令
  151. * @return mixed
  152. */
  153. static function doSql($sql='') {
  154. if(self::isMainIps($sql)) {
  155. return self::execute($sql);
  156. }else {
  157. return self::getAll($sql);
  158. }
  159. }
  160. /**
  161. * 根據(jù)指定ID查找表中記錄(僅用于單表操作)
  162. * @access function
  163. * @param integer $priId 主鍵ID
  164. * @param string $tables 數(shù)據(jù)表名
  165. * @param string $fields 字段名
  166. * @return ArrayObject 表記錄
  167. */
  168. static function findById($tabName,$priId,$fields='*'){
  169. $sql = 'SELECT %s FROM %s WHERE id=%d';
  170. return self::getRow(sprintf($sql, self::parseFields($fields), $tabName, $priId));
  171. }
  172. /**
  173. * 查找記錄
  174. * @access function
  175. * @param string $tables 數(shù)據(jù)表名
  176. * @param mixed $where 查詢條件
  177. * @param string $fields 字段名
  178. * @param string $order 排序
  179. * @param string $limit 取多少條數(shù)據(jù)
  180. * @param string $group 分組
  181. * @param string $having
  182. * @param boolean $lock 是否加鎖
  183. * @return ArrayObject
  184. */
  185. static function find($tables,$where="",$fields='*',$order=null,$limit=null,$group=null,$having=null) {
  186. $sql = 'SELECT '.self::parseFields($fields)
  187. .' FROM '.$tables
  188. .self::parseWhere($where)
  189. .self::parseGroup($group)
  190. .self::parseHaving($having)
  191. .self::parseOrder($order)
  192. .self::parseLimit($limit);
  193. $dataAll = self::getAll($sql);
  194. if(count($dataAll)==1){$rlt=$dataAll[0];}else{$rlt=$dataAll;}
  195. return $rlt;
  196. }
  197. /**
  198. * 插入(單條)記錄
  199. * @access function
  200. * @param mixed $data 數(shù)據(jù)
  201. * @param string $table 數(shù)據(jù)表名
  202. * @return false | integer
  203. */
  204. function add($data,$table) {
  205. //過濾提交數(shù)據(jù)
  206. $data=self::filterPost($table,$data);
  207. foreach ($data as $key=>$val){
  208. if(is_array($val) && strtolower($val[0]) == 'exp') {
  209. $val = $val[1]; // 使用表達(dá)式 ???
  210. }elseif (is_scalar($val)){
  211. $val = self::fieldFormat($val);
  212. }else{
  213. // 去掉復(fù)合對象
  214. continue;
  215. }
  216. $data[$key] = $val;
  217. }
  218. $fields = array_keys($data);
  219. array_walk($fields, array($this, 'addSpecialChar'));
  220. $fieldsStr = implode(',', $fields);
  221. $values = array_values($data);
  222. $valuesStr = implode(',', $values);
  223. $sql = 'INSERT INTO '.$table.' ('.$fieldsStr.') VALUES ('.$valuesStr.')';
  224. return self::execute($sql);
  225. }
  226. /**
  227. * 更新記錄
  228. * @access function
  229. * @param mixed $sets 數(shù)據(jù)
  230. * @param string $table 數(shù)據(jù)表名
  231. * @param string $where 更新條件
  232. * @param string $limit
  233. * @param string $order
  234. * @return false | integer
  235. */
  236. static function update($sets,$table,$where,$limit=0,$order='') {
  237. $sets = self::filterPost($table,$sets);
  238. $sql = 'UPDATE '.$table.' SET '.self::parseSets($sets).self::parseWhere($where).self::parseOrder($order).self::parseLimit($limit);
  239. return self::execute($sql);
  240. }
  241. /**
  242. * 保存某個字段的值
  243. * @access function
  244. * @param string $field 要保存的字段名
  245. * @param string $value 字段值
  246. * @param string $table 數(shù)據(jù)表
  247. * @param string $where 保存條件
  248. * @param boolean $asString 字段值是否為字符串
  249. * @return void
  250. */
  251. static function setField($field, $value, $table, $condition="", $asString=false) {
  252. // 如果有'(' 視為 SQL指令更新 否則 更新字段內(nèi)容為純字符串
  253. if(false === strpos($value,'(') || $asString) $value = '"'.$value.'"';
  254. $sql = 'UPDATE '.$table.' SET '.$field.'='.$value.self::parseWhere($condition);
  255. return self::execute($sql);
  256. }
  257. /**
  258. * 刪除記錄
  259. * @access function
  260. * @param mixed $where 為條件Map、Array或者String
  261. * @param string $table 數(shù)據(jù)表名
  262. * @param string $limit
  263. * @param string $order
  264. * @return false | integer
  265. */
  266. static function remove($where,$table,$limit='',$order='') {
  267. $sql = 'DELETE FROM '.$table.self::parseWhere($where).self::parseOrder($order).self::parseLimit($limit);
  268. return self::execute($sql);
  269. }
  270. /**
  271. +----------------------------------------------------------
  272. * 修改或保存數(shù)據(jù)(僅用于單表操作)
  273. * 有主鍵ID則為修改,無主鍵ID則為增加
  274. * 修改記錄:
  275. +----------------------------------------------------------
  276. * @access function
  277. +----------------------------------------------------------
  278. * @param $tabName 表名
  279. * @param $aPost 提交表單的 $_POST
  280. * @param $priId 主鍵ID
  281. * @param $aNot 要排除的一個字段或數(shù)組
  282. * @param $aCustom 自定義的一個數(shù)組,附加到數(shù)據(jù)庫中保存
  283. * @param $isExits 是否已經(jīng)存在 存在:true, 不存在:false
  284. +----------------------------------------------------------
  285. * @return Boolean 修改或保存是否成功
  286. +----------------------------------------------------------
  287. */
  288. function saveOrUpdate($tabName, $aPost, $priId="", $aNot="", $aCustom="", $isExits=false) {
  289. if(empty($tabName) || !is_array($aPost) || is_int($aNot)) return false;
  290. if(is_string($aNot) && !empty($aNot)) $aNot = array($aNot);
  291. if(is_array($aNot) && is_int(key($aNot))) $aPost = array_diff_key($aPost, array_flip($aNot));
  292. if(is_array($aCustom) && is_string(key($aCustom))) $aPost = array_merge($aPost,$aCustom);
  293. if (empty($priId) && !$isExits) { //新增
  294. $aPost = array_filter($aPost, array($this, 'removeEmpty'));
  295. return self::add($aPost, $tabName);
  296. } else { //修改
  297. return self::update($aPost, $tabName, "id=".$priId);
  298. }
  299. }
  300. /**
  301. * 獲取最近一次查詢的sql語句
  302. * @access function
  303. * @param
  304. * @return String 執(zhí)行的SQL
  305. */
  306. static function getLastSql() {
  307. $link = self::$link;
  308. if ( !$link ) return false;
  309. return self::$queryStr;
  310. }
  311. /**
  312. * 獲取最后插入的ID
  313. * @access function
  314. * @param
  315. * @return integer 最后插入時的數(shù)據(jù)ID
  316. */
  317. static function getLastInsId(){
  318. $link = self::$link;
  319. if ( !$link ) return false;
  320. return self::$lastInsertId;
  321. }
  322. /**
  323. * 獲取DB版本
  324. * @access function
  325. * @param
  326. * @return string
  327. */
  328. static function getDbVersion(){
  329. $link = self::$link;
  330. if ( !$link ) return false;
  331. return self::$dbVersion;
  332. }
  333. /**
  334. * 取得數(shù)據(jù)庫的表信息
  335. * @access function
  336. * @return array
  337. */
  338. static function getTables() {
  339. $info = array();
  340. if(self::query("SHOW TABLES")) {
  341. $result = self::getAll();
  342. foreach ($result as $key => $val) {
  343. $info[$key] = current($val);
  344. }
  345. }
  346. return $info;
  347. }
  348. /**
  349. * 取得數(shù)據(jù)表的字段信息
  350. * @access function
  351. * @return array
  352. */
  353. static function getFields($tableName) {
  354. // 獲取數(shù)據(jù)庫聯(lián)接
  355. $link = self::$link;
  356. $sql = "SELECT
  357. ORDINAL_POSITION ,COLUMN_NAME, COLUMN_TYPE, DATA_TYPE,
  358. IF(ISNULL(CHARACTER_MAXIMUM_LENGTH), (NUMERIC_PRECISION + NUMERIC_SCALE), CHARACTER_MAXIMUM_LENGTH) AS MAXCHAR,
  359. IS_NULLABLE, COLUMN_DEFAULT, COLUMN_KEY, EXTRA, COLUMN_COMMENT
  360. FROM
  361. INFORMATION_SCHEMA.COLUMNS
  362. WHERE
  363. TABLE_NAME = :tabName AND TABLE_SCHEMA='".DB_NAME."'";
  364. self::$queryStr = sprintf($sql, $tableName);
  365. $sth = $link->prepare($sql);
  366. $sth->bindParam(':tabName', $tableName);
  367. $sth->execute();
  368. $result = $sth->fetchAll(constant('PDO::FETCH_ASSOC'));
  369. $info = array();
  370. foreach ($result as $key => $val) {
  371. $info[$val['COLUMN_NAME']] = array(
  372. 'postion' => $val['ORDINAL_POSITION'],
  373. 'name' => $val['COLUMN_NAME'],
  374. 'type' => $val['COLUMN_TYPE'],
  375. 'd_type' => $val['DATA_TYPE'],
  376. 'length' => $val['MAXCHAR'],
  377. 'notnull' => (strtolower($val['IS_NULLABLE']) == "no"),
  378. 'default' => $val['COLUMN_DEFAULT'],
  379. 'primary' => (strtolower($val['COLUMN_KEY']) == 'pri'),
  380. 'autoInc' => (strtolower($val['EXTRA']) == 'auto_increment'),
  381. 'comment' => $val['COLUMN_COMMENT']
  382. );
  383. }
  384. // 有錯誤則拋出異常
  385. self::haveErrorThrowException();
  386. return $info;
  387. }
  388. /**
  389. * 關(guān)閉數(shù)據(jù)庫
  390. * @access function
  391. */
  392. static function close() {
  393. self::$link = null;
  394. }
  395. /**
  396. * SQL指令安全過濾
  397. * @access function
  398. * @param string $str SQL指令
  399. * @return string
  400. */
  401. static function escape_string($str) {
  402. return addslashes($str);
  403. }
  404. /************************/
  405. /* 內(nèi)部操作方法 */
  406. /************************/
  407. /**
  408. * 有出錯拋出異常
  409. * @access function
  410. * @return
  411. */
  412. static function haveErrorThrowException() {
  413. $obj = empty(self::$PDOStatement) ? self::$link : self::$PDOStatement;
  414. $arrError = $obj->errorInfo();
  415. if($arrError[0] !== '00000') { // 有錯誤信息
  416. self::$error = $arrError[0]."|".$arrError[2]. "
    [ SQL ] : ".self::$queryStr."
    ";
  417. self::throw_exception(self::$error);
  418. return false;
  419. }
  420. //主要針對execute()方法拋出異常
  421. if(self::$queryStr=='')self::throw_exception('Query was empty

    [ SQL語句 ] :');
  422. }
  423. /**
  424. * where分析
  425. * @access function
  426. * @param mixed $where 查詢條件
  427. * @return string
  428. */
  429. static function parseWhere($where) {
  430. $whereStr = '';
  431. if(is_string($where) || is_null($where)) {
  432. $whereStr = $where;
  433. }
  434. return empty($whereStr)?'':' WHERE '.$whereStr;
  435. }
  436. /**
  437. * order分析
  438. * @access function
  439. * @param mixed $order 排序
  440. * @return string
  441. */
  442. static function parseOrder($order) {
  443. $orderStr = '';
  444. if(is_array($order))
  445. $orderStr .= ' ORDER BY '.implode(',', $order);
  446. else if(is_string($order) && !empty($order))
  447. $orderStr .= ' ORDER BY '.$order;
  448. return $orderStr;
  449. }
  450. /**
  451. * limit分析
  452. * @access function
  453. * @param string $limit
  454. * @return string
  455. */
  456. static function parseLimit($limit) {
  457. $limitStr = '';
  458. if(is_array($limit)) {
  459. if(count($limit)>1)
  460. $limitStr .= ' LIMIT '.$limit[0].' , '.$limit[1].' ';
  461. else
  462. $limitStr .= ' LIMIT '.$limit[0].' ';
  463. } else if(is_string($limit) && !empty($limit)) {
  464. $limitStr .= ' LIMIT '.$limit.' ';
  465. }
  466. return $limitStr;
  467. }
  468. /**
  469. * group分析
  470. * @access function
  471. * @param mixed $group
  472. * @return string
  473. */
  474. static function parseGroup($group) {
  475. $groupStr = '';
  476. if(is_array($group))
  477. $groupStr .= ' GROUP BY '.implode(',', $group);
  478. else if(is_string($group) && !empty($group))
  479. $groupStr .= ' GROUP BY '.$group;
  480. return empty($groupStr)?'':$groupStr;
  481. }
  482. /**
  483. * having分析
  484. * @access function
  485. * @param string $having
  486. * @return string
  487. */
  488. static function parseHaving($having) {
  489. $havingStr = '';
  490. if(is_string($having) && !empty($having))
  491. $havingStr .= ' HAVING '.$having;
  492. return $havingStr;
  493. }
  494. /**
  495. * fields分析
  496. * @access function
  497. * @param mixed $fields
  498. * @return string
  499. */
  500. function parseFields($fields) {
  501. if(is_array($fields)) {
  502. array_walk($fields, array($this, 'addSpecialChar'));
  503. $fieldsStr = implode(',', $fields);
  504. }else if(is_string($fields) && !empty($fields)) {
  505. if( false === strpos($fields,'`') ) {
  506. $fields = explode(',',$fields);
  507. array_walk($fields, array($this, 'addSpecialChar'));
  508. $fieldsStr = implode(',', $fields);
  509. }else {
  510. $fieldsStr = $fields;
  511. }
  512. }else $fieldsStr = '*';
  513. return $fieldsStr;
  514. }
  515. /**
  516. * sets分析,在更新數(shù)據(jù)時調(diào)用
  517. * @access function
  518. * @param mixed $values
  519. * @return string
  520. */
  521. private function parseSets($sets) {
  522. $setsStr = '';
  523. if(is_array($sets)){
  524. foreach ($sets as $key=>$val){
  525. $key = self::addSpecialChar($key);
  526. $val = self::fieldFormat($val);
  527. $setsStr .= "$key = ".$val.",";
  528. }
  529. $setsStr = substr($setsStr,0,-1);
  530. }else if(is_string($sets)) {
  531. $setsStr = $sets;
  532. }
  533. return $setsStr;
  534. }
  535. /**
  536. * 字段格式化
  537. * @access function
  538. * @param mixed $value
  539. * @return mixed
  540. */
  541. static function fieldFormat(&$value) {
  542. if(is_int($value)) {
  543. $value = intval($value);
  544. } else if(is_float($value)) {
  545. $value = floatval($value);
  546. } elseif(preg_match('/^\(\w*(\+|\-|\*|\/)?\w*\)$/i',$value)){
  547. // 支持在字段的值里面直接使用其它字段
  548. // 例如 (score+1) (name) 必須包含括號
  549. $value = $value;
  550. }else if(is_string($value)) {
  551. $value = '\''.self::escape_string($value).'\'';
  552. }
  553. return $value;
  554. }
  555. /**
  556. * 字段和表名添加` 符合
  557. * 保證指令中使用關(guān)鍵字不出錯 針對mysql
  558. * @access function
  559. * @param mixed $value
  560. * @return mixed
  561. */
  562. static function addSpecialChar(&$value) {
  563. if( '*' == $value || false !== strpos($value,'(') || false !== strpos($value,'.') || false !== strpos($value,'`')) {
  564. //如果包含* 或者 使用了sql方法 則不作處理
  565. } elseif(false === strpos($value,'`') ) {
  566. $value = '`'.trim($value).'`';
  567. }
  568. return $value;
  569. }
  570. /**
  571. +----------------------------------------------------------
  572. * 去掉空元素
  573. +----------------------------------------------------------
  574. * @access function
  575. +----------------------------------------------------------
  576. * @param mixed $value
  577. +----------------------------------------------------------
  578. * @return mixed
  579. +----------------------------------------------------------
  580. */
  581. static function removeEmpty($value){
  582. return !empty($value);
  583. }
  584. /**
  585. * 執(zhí)行查詢 主要針對 SELECT, SHOW 等指令
  586. * @access function
  587. * @param string $sql sql指令
  588. * @return mixed
  589. */
  590. static function query($sql='') {
  591. // 獲取數(shù)據(jù)庫聯(lián)接
  592. $link = self::$link;
  593. if ( !$link ) return false;
  594. self::$queryStr = $sql;
  595. //釋放前次的查詢結(jié)果
  596. if ( !empty(self::$PDOStatement) ) self::free();
  597. self::$PDOStatement = $link->prepare(self::$queryStr);
  598. $bol = self::$PDOStatement->execute();
  599. // 有錯誤則拋出異常
  600. self::haveErrorThrowException();
  601. return $bol;
  602. }
  603. /**
  604. * 數(shù)據(jù)庫操作方法
  605. * @access function
  606. * @param string $sql 執(zhí)行語句
  607. * @param boolean $lock 是否鎖定(默認(rèn)不鎖定)
  608. * @return void
  609. public function execute($sql='',$lock=false) {
  610. if(empty($sql)) $sql = $this->queryStr;
  611. return $this->_execute($sql);
  612. }*/
  613. /**
  614. * 執(zhí)行語句 針對 INSERT, UPDATE 以及DELETE
  615. * @access function
  616. * @param string $sql sql指令
  617. * @return integer
  618. */
  619. static function execute($sql='') {
  620. // 獲取數(shù)據(jù)庫聯(lián)接
  621. $link = self::$link;
  622. if ( !$link ) return false;
  623. self::$queryStr = $sql;
  624. //釋放前次的查詢結(jié)果
  625. if ( !empty(self::$PDOStatement) ) self::free();
  626. $result = $link->exec(self::$queryStr);
  627. // 有錯誤則拋出異常
  628. self::haveErrorThrowException();
  629. if ( false === $result) {
  630. return false;
  631. } else {
  632. self::$numRows = $result;
  633. self::$lastInsertId = $link->lastInsertId();
  634. return self::$numRows;
  635. }
  636. }
  637. /**
  638. * 是否為數(shù)據(jù)庫更改操作
  639. * @access private
  640. * @param string $query SQL指令
  641. * @return boolen 如果是查詢操作返回false
  642. */
  643. static function isMainIps($query) {
  644. $queryIps = 'INSERT|UPDATE|DELETE|REPLACE|CREATE|DROP|LOAD DATA|SELECT .* INTO|COPY|ALTER|GRANT|REVOKE|LOCK|UNLOCK';
  645. if (preg_match('/^\s*"?(' . $queryIps . ')\s+/i', $query)) {
  646. return true;
  647. }
  648. return false;
  649. }
  650. /**
  651. * 過濾POST提交數(shù)據(jù)
  652. * @access private
  653. * @param mixed $data POST提交數(shù)據(jù)
  654. * @param string $table 數(shù)據(jù)表名
  655. * @return mixed $newdata
  656. */
  657. static function filterPost($table,$data) {
  658. $table_column = self::getFields($table);
  659. $newdata=array();
  660. foreach ($table_column as $key=>$val){
  661. if(array_key_exists($key,$data) && ($data[$key])!==''){
  662. $newdata[$key] = $data[$key];
  663. }
  664. }
  665. return $newdata;
  666. }
  667. /**
  668. * 啟動事務(wù)
  669. * @access function
  670. * @return void
  671. */
  672. static function startTrans() {
  673. //數(shù)據(jù)rollback 支持
  674. $link = self::$link;
  675. if ( !$link ) return false;
  676. if (self::$transTimes == 0) {
  677. $link->beginTransaction();
  678. }
  679. self::$transTimes++;
  680. return ;
  681. }
  682. /**
  683. * 用于非自動提交狀態(tài)下面的查詢提交
  684. * @access function
  685. * @return boolen
  686. */
  687. static function commit() {
  688. $link = self::$link;
  689. if ( !$link ) return false;
  690. if (self::$transTimes > 0) {
  691. $result = $link->commit();
  692. self::$transTimes = 0;
  693. if(!$result){
  694. self::throw_exception(self::$error());
  695. return false;
  696. }
  697. }
  698. return true;
  699. }
  700. /**
  701. * 事務(wù)回滾
  702. * @access function
  703. * @return boolen
  704. */
  705. public function rollback() {
  706. $link = self::$link;
  707. if ( !$link ) return false;
  708. if (self::$transTimes > 0) {
  709. $result = $link->rollback();
  710. self::$transTimes = 0;
  711. if(!$result){
  712. self::throw_exception(self::$error());
  713. return false;
  714. }
  715. }
  716. return true;
  717. }
  718. /**

  719. * 錯誤處理
  720. * @access function
  721. * @return void
  722. */
  723. static function throw_exception($err){
  724. echo '
    ERROR:'.$err.'
    ';
  725. }
  726. }
復(fù)制代碼


本站聲明
本文內(nèi)容由網(wǎng)友自發(fā)貢獻(xiàn),版權(quán)歸原作者所有,本站不承擔(dān)相應(yīng)法律責(zé)任。如您發(fā)現(xiàn)有涉嫌抄襲侵權(quán)的內(nèi)容,請聯(lián)系admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費(fèi)脫衣服圖片

Undresser.AI Undress

Undresser.AI Undress

人工智能驅(qū)動的應(yīng)用程序,用于創(chuàng)建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用于從照片中去除衣服的在線人工智能工具。

Clothoff.io

Clothoff.io

AI脫衣機(jī)

Video Face Swap

Video Face Swap

使用我們完全免費(fèi)的人工智能換臉工具輕松在任何視頻中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費(fèi)的代碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

功能強(qiáng)大的PHP集成開發(fā)環(huán)境

Dreamweaver CS6

Dreamweaver CS6

視覺化網(wǎng)頁開發(fā)工具

SublimeText3 Mac版

SublimeText3 Mac版

神級代碼編輯軟件(SublimeText3)

對基于PHP的API進(jìn)行版本控制的最佳實踐是什么? 對基于PHP的API進(jìn)行版本控制的最佳實踐是什么? Jun 14, 2025 am 12:27 AM

基于toversionaphp,useUrl deuseUrl specteringforclarityAndEsofRouting,單獨的codetoavoidConflicts,dremecateOldVersionswithClearCommunication,andConsiderCustomHeadeSerlySerallyWhennEnncelsy.startbyplacingtheversionIntheUrl(E.G.,epi/api/v

如何在PHP中實施身份驗證和授權(quán)? 如何在PHP中實施身份驗證和授權(quán)? Jun 20, 2025 am 01:03 AM

tosecurelyhandleauthenticationandationallizationInphp,lofterTheSesteps:1.AlwaysHashPasswordSwithPassword_hash()andverifyusingspasspassword_verify(),usepreparedStatatementStopreventsqlineptions,andStoreSeruserDatain usseruserDatain $ _sessiveferterlogin.2.implementrole-2.imaccessccsccccccccccccccccccccccccc.

PHP中的程序和面向?qū)ο蟮木幊谭独g有什么區(qū)別? PHP中的程序和面向?qū)ο蟮木幊谭独g有什么區(qū)別? Jun 14, 2025 am 12:25 AM

procemal and object-tiriendedprogromming(oop)inphpdiffersimplessintustructure,可重復(fù)使用性和datahandling.1.procedural-Progrogursmingusesfunctimesfunctionsormanized sequalized sequalized sequiential,poiperforsmallscripts.2.OpporganizesCodeOrganizescodeOdeIntsocloceSandObjects,ModelingReal-Worlden-Worlden

PHP中有哪些弱參考(弱圖),何時有用? PHP中有哪些弱參考(弱圖),何時有用? Jun 14, 2025 am 12:25 AM

PHPdoesnothaveabuilt-inWeakMapbutoffersWeakReferenceforsimilarfunctionality.1.WeakReferenceallowsholdingreferenceswithoutpreventinggarbagecollection.2.Itisusefulforcaching,eventlisteners,andmetadatawithoutaffectingobjectlifecycles.3.YoucansimulateaWe

如何在PHP中安全地處理文件上傳? 如何在PHP中安全地處理文件上傳? Jun 19, 2025 am 01:05 AM

要安全處理PHP中的文件上傳,核心在于驗證文件類型、重命名文件并限制權(quán)限。1.使用finfo_file()檢查真實MIME類型,僅允許特定類型如image/jpeg;2.用uniqid()生成隨機(jī)文件名,存儲至非Web根目錄;3.通過php.ini和HTML表單限制文件大小,設(shè)置目錄權(quán)限為0755;4.使用ClamAV掃描惡意軟件,增強(qiáng)安全性。這些步驟有效防止安全漏洞,確保文件上傳過程安全可靠。

如何與PHP的NOSQL數(shù)據(jù)庫(例如MongoDB,Redis)進(jìn)行交互? 如何與PHP的NOSQL數(shù)據(jù)庫(例如MongoDB,Redis)進(jìn)行交互? Jun 19, 2025 am 01:07 AM

是的,PHP可以通過特定擴(kuò)展或庫與MongoDB和Redis等NoSQL數(shù)據(jù)庫交互。首先,使用MongoDBPHP驅(qū)動(通過PECL或Composer安裝)創(chuàng)建客戶端實例并操作數(shù)據(jù)庫及集合,支持插入、查詢、聚合等操作;其次,使用Predis庫或phpredis擴(kuò)展連接Redis,執(zhí)行鍵值設(shè)置與獲取,推薦phpredis用于高性能場景,Predis則便于快速部署;兩者均適用于生產(chǎn)環(huán)境且文檔完善。

PHP中==(松散比較)和===(嚴(yán)格的比較)之間有什么區(qū)別? PHP中==(松散比較)和===(嚴(yán)格的比較)之間有什么區(qū)別? Jun 19, 2025 am 01:07 AM

在PHP中,==與===的主要區(qū)別在于類型檢查的嚴(yán)格程度。==在比較前會進(jìn)行類型轉(zhuǎn)換,例如5=="5"返回true,而===要求值和類型都相同才會返回true,例如5==="5"返回false。使用場景上,===更安全應(yīng)優(yōu)先使用,==僅在需要類型轉(zhuǎn)換時使用。

如何在PHP( - , *, /,%)中執(zhí)行算術(shù)操作? 如何在PHP( - , *, /,%)中執(zhí)行算術(shù)操作? Jun 19, 2025 pm 05:13 PM

PHP中使用基本數(shù)學(xué)運(yùn)算的方法如下:1.加法用 號,支持整數(shù)和浮點數(shù),也可用于變量,字符串?dāng)?shù)字會自動轉(zhuǎn)換但不推薦依賴;2.減法用-號,變量同理,類型轉(zhuǎn)換同樣適用;3.乘法用*號,適用于數(shù)字及類似字符串;4.除法用/號,需避免除以零,并注意結(jié)果可能是浮點數(shù);5.取模用%號,可用于判斷奇偶數(shù),處理負(fù)數(shù)時余數(shù)符號與被除數(shù)一致。正確使用這些運(yùn)算符的關(guān)鍵在于確保數(shù)據(jù)類型清晰并處理好邊界情況。

See all articles