PHP的PDO常用类库实例分析,pdo类库实例分析
本文实例讲述了PHP的PDO常用类库。分享给大家供大家参考,具体如下:
1、Db.class.php 连接数据库
<?php // 连接数据库 class Db { static public function getDB() { try { $pdo = new PDO(DB_DSN, DB_USER, DB_PWD); $pdo->setAttribute(PDO::ATTR_PERSISTENT, true); // 设置数据库连接为持久连接 $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // 设置抛出错误 $pdo->setAttribute(PDO::ATTR_ORACLE_NULLS, true); // 设置当字符串为空转换为 SQL 的 NULL $pdo->query('SET NAMES utf8'); // 设置数据库编码 } catch (PDOException $e) { exit('数据库连接错误,错误信息:'. $e->getMessage()); } return $pdo; } } ?>
2、Model.class.php 数据库操作类
<?php /** * 数据库操作类库 * author Lee. * Last modify $Date: 2012-1-19 13:59;04 $ */ class M { private $_db; //数据库句柄 public $_sql; //SQL语句 /** * 构造方法 */ public function __construct() { $this->_db = Db::getDB(); } /** * 数据库添加操作 * @param string $tName 表名 * @param array $field 字段数组 * @param array $val 值数组 * @param bool $is_lastInsertId 是否返回添加ID * @return int 默认返回成功与否,$is_lastInsertId 为true,返回添加ID */ public function insert($tName, $fields, $vals, $is_lastInsertId=FALSE) { try { if (!is_array($fields) || !is_array($vals)) exit($this->getError(__FUNCTION__, __LINE__)); $fields = $this->formatArr($fields); $vals = $this->formatArr($vals, false); $tName = $this->formatTabName($tName); $this->_sql = "INSERT INTO {$tName} ({$fields}) VALUES ({$vals})"; if (!$is_lastInsertId) { $row = $this->_db->exec($this->_sql); return $row; } else { $this->_db->exec($this->_sql); $lastId = (int)$this->_db->lastInsertId(); return $lastId; } } catch (PDOException $e) { exit($e->getMessage()); } } /** * 数据库修改操作 * @param string $tName 表名 * @param array $field 字段数组 * @param array $val 值数组 * @param string $condition 条件 * @return int 受影响的行数 */ public function update($tName, $fieldVal, $condition) { try { if (!is_array($fieldVal) || !is_string($tName) || !is_string($condition)) exit($this->getError(__FUNCTION__, __LINE__)); $tName = $this->formatTabName($tName); $upStr = ''; foreach ($fieldVal as $k=>$v) { $upStr .= '`'.$k . '`=' . '\'' . $v . '\'' . ','; } $upStr = rtrim($upStr, ','); $this->_sql = "UPDATE {$tName} SET {$upStr} WHERE {$condition}"; $row = $this->_db->exec($this->_sql); return $row; } catch (PDOException $e) { exit($e->getMessage()); } } /** * 数据库删除操作(注:必须添加 where 条件) * @param string $tName 表名 * @param string $condition 条件 * @return int 受影响的行数 */ public function del($tName, $condition) { try { if (!is_string($tName) || !is_string($condition)) exit($this->getError(__FUNCTION__, __LINE__)); $tName= $this->formatTabName($tName); $this->_sql = "DELETE FROM {$tName} WHERE {$condition}"; $row = $this->_db->exec($this->_sql); return $row; } catch (PDOException $e) { exit($e->getMessage()); } } /** * 返回表总个数 * @param string $tName 表名 * @param string $condition 条件 * @return int */ public function total($tName, $condition='') { try { if (!is_string($tName)) exit($this->getError(__FUNCTION__, __LINE__)); $tName = $this->formatTabName($tName); $this->_sql = "SELECT COUNT(*) AS total FROM {$tName}" . ($condition=='' ? '' : ' WHERE ' . $condition); $re = $this->_db->query($this->_sql); foreach ($re as $v) { $total = $v['total']; } return (int)$total; } catch (PDOException $e) { exit($e->getMessage()); } } /** * 数据库删除多条数据 * @param string $tName 表名 * @param string $field 依赖字段 * @param array $ids 删除数组 * @return int 受影响的行数 */ public function delMulti($tName, $field, $ids) { try { if (!is_string($tName) || !is_array($ids)) exit($this->getError(__FUNCTION__, __LINE__)); $delStr = ''; $tName = $this->formatTabName($tName); $field = $this->formatTabName($field); foreach ($ids as $v) { $delStr .= $v . ','; } $delStr = rtrim($delStr, ','); $this->_sql = "DELETE FROM {$tName} WHERE {$field} IN ({$delStr})"; $row = $this->_db->exec($this->_sql); return $row; } catch (PDOException $e) { exit($e->getMessage()); } } /** * 获取表格的最后主键(注:针对 INT 类型) * @param string $tName 表名 * @return int */ public function insertId($tName) { try { if (!is_string($tName)) exit($this->getError(__FUNCTION__, __LINE__)); $this->_sql = "SHOW TABLE STATUS LIKE '{$tName}'"; $result = $this->_db->query($this->_sql); $insert_id = 0; foreach ($result as $v) { $insert_id = $v['Auto_increment']; } return (int)$insert_id; } catch (PDOException $e) { exit($e->getMessage()); } } /** * 检查数据是否已经存在(依赖条件) * @param string $tName 表名 * @param string $field 依赖的字段 * @return bool */ public function exists($tName, $condition) { try { if (!is_string($tName) || !is_string($condition)) exit($this->getError(__FUNCTION__, __LINE__)); $tName = $this->formatTabName($tName); $this->_sql = "SELECT COUNT(*) AS total FROM {$tName} WHERE {$condition}"; $result = $this->_db->query($this->_sql); foreach ($result as $v) { $b = $v['total']; } if ($b) { return true; } else { return false; } } catch (PDOException $e) { exit($e->getMessage()); } } /** * 检查数据是否已经存在(依赖 INT 主键) * @param string $tName 表名 * @param string $primary 主键 * @param int $id 主键值 * @return bool */ public function existsByPK($tName, $primary, $id) { try { if (!is_string($tName) || !is_string($primary) || !is_int($id)) exit($this->getError(__FUNCTION__, __LINE__)); $tName = $this->formatTabName($tName); $this->_sql = "SELECT COUNT(*) AS total FROM {$tName} WHERE {$primary} = ". $id; $result = $this->_db->query($this->_sql); foreach ($result as $v) { $b = $v['total']; } if ($b) { return true; } else { return false; } } catch (PDOException $e) { exit($e->getMessage()); } } /** * 预处理删除(注:针对主键为 INT 类型,推荐使用) * @param string $tName 表名 * @param string $primary 主键字段 * @param int or array or string $ids 如果是删除一条为 INT,多条为 array,删除一个范围为 string * @return int 返回受影响的行数 */ public function delByPK($tName, $primary, $ids, $mult=FALSE) { try { if (!is_string($tName) || !is_string($primary) || (!is_int($ids) && !is_array($ids) && !is_string($ids)) || !is_bool($mult)) exit($this->getError(__FUNCTION__, __LINE__)); $tName = $this->formatTabName($tName); $stmt = $this->_db->prepare("DELETE FROM {$tName} WHERE {$primary}=?"); if (!$mult) { $stmt->bindParam(1, $ids); $row = $stmt->execute(); } else { if (is_array($ids)) { $row = 0; foreach ($ids as $v) { $stmt->bindParam(1, $v); if ($stmt->execute()) { $row++; } } } elseif (is_string($ids)) { if (!strpos($ids, '-')) exit($this->getError(__FUNCTION__, __LINE__)); $split = explode('-', $ids); if (count($split)!=2 || $split[0]>$split[1]) exit($this->getError(__FUNCTION__, __LINE__)); $i = null; $count = $split[1]-$split[0]+1; for ($i=0; $i<$count; $i++) { $idArr[$i] = $split[0]++; } $idStr = ''; foreach ($idArr as $id) { $idStr .= $id . ','; } $idStr = rtrim($idStr, ','); $this->_sql ="DELETE FROM {$tName} WHERE {$primary} in ({$idStr})"; $row = $this->_db->exec($this->_sql); } } return $row; } catch (PDOException $e) { exit($e->getMessage()); } } /** * 返回单个字段数据或单条记录 * @param string $tName 表名 * @param string $condition 条件 * @param string or array $fields 返回的字段,默认是* * @return string || array */ public function getRow($tName, $condition='', $fields="*") { try { if (!is_string($tName) || !is_string($condition) || !is_string($fields) || empty($fields)) exit($this->getError(__FUNCTION__, __LINE__)); $tName = $this->formatTabName($tName); $this->_sql = "SELECT {$fields} FROM {$tName} "; $this->_sql .= ($condition=='' ? '' : "WHERE {$condition}") . " LIMIT 1"; $sth = $this->_db->prepare($this->_sql); $sth->execute(); $result = $sth->fetch(PDO::FETCH_ASSOC); if ($fields === '*') { return $result; } else { return $result[$fields]; } } catch (PDOException $e) { exit($e->getMessage()); } } /** * 返回多条数据 * @param string $tName 表名 * @param string $fields 返回字段,默认为* * @param string $condition 条件 * @param string $order 排序 * @param string $limit 显示个数 * @return PDOStatement */ public function getAll($tName, $fields='*', $condition='', $order='', $limit='') { try { if (!is_string($tName) || !is_string($fields) || !is_string($condition) || !is_string($order) || !is_string($limit)) exit($this->getError(__FUNCTION__, __LINE__)); $tName = $this->formatTabName($tName); $fields = ($fields=='*' || $fields=='') ? '*' : $fields; $condition = $condition=='' ? '' : " WHERE ". $condition ; $order = $order=='' ? '' : " ORDER BY ". $order; $limit = $limit=='' ? '' : " LIMIT ". $limit; $this->_sql = "SELECT {$fields} FROM {$tName} {$condition} {$order} {$limit}"; $sth = $this->_db->prepare($this->_sql); $sth->execute(); $result = $sth->fetchAll(PDO::FETCH_ASSOC); return $result; } catch (PDOException $e) { exit($e->getMessage()); } } /** * 格式化数组(表结构和值) * @param array $field * @param bool $isField * @return string */ private function formatArr($field, $isField=TRUE) { if (!is_array($field)) exit($this->getError(__FUNCTION__, __LINE__)); $fields = ''; if ($isField) { foreach ($field as $v) { $fields .= '`'.$v.'`,'; } } else { foreach ($field as $v) { $fields .= '\''.$v.'\''.','; } } $fields = rtrim($fields, ','); return $fields; } /** * 格式化问号 * @param int $count 数量 * @return string 返回格式化后的字符串 */ private function formatMark($count) { $str = ''; if (!is_int($count)) exit($this->getError(__FUNCTION__, __LINE__)); if ($count==1) return '?'; for ($i=0; $i<$count; $i++) { $str .= '?,'; } return rtrim($str, ','); } /** * 错误提示 * @param string $fun * @return string */ private function getError($fun, $line) { return __CLASS__ . '->' . $fun . '() line<font color="red">'. $line .'</font> ERROR!'; } /** * 处理表名 * @param string $tName * @return string */ private function formatTabName($tName) { return '`' . trim($tName, '`') . '`'; } /** * 析构方法 */ public function __destruct() { $this->_db = null; } }
更多关于PHP相关内容感兴趣的读者可查看本站专题:《php curl用法总结》、《PHP运算与运算符用法总结》、《PHP网络编程技巧总结》、《PHP基本语法入门教程》、《php操作office文档技巧总结(包括word,excel,access,ppt)》、《php日期与时间用法总结》、《php面向对象程序设计入门教程》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》
希望本文所述对大家PHP程序设计有所帮助。
您可能感兴趣的文章:
- 在PHP中PDO解决中文乱码问题的一些补充
- php PDO中文乱码解决办法
- PHP中PDO的事务处理分析
- PHP的PDO操作简单示例
- PHP5.2中PDO的简单使用方法
- php中PDO方式实现数据库的增删改查
- php中mysql连接方式PDO使用详解
- php中数据库连接方式pdo和mysqli对比分析
- PHP PDO fetch 模式各种参数的输出结果一览
- php使用PDO方法详解
- PHP使用PDO操作数据库的乱码问题解决方法

php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

实现方法:1、使用“sleep(延迟秒数)”语句,可延迟执行函数若干秒;2、使用“time_nanosleep(延迟秒数,延迟纳秒数)”语句,可延迟执行函数若干秒和纳秒;3、使用“time_sleep_until(time()+7)”语句。

php字符串有下标。在PHP中,下标不仅可以应用于数组和对象,还可应用于字符串,利用字符串的下标和中括号“[]”可以访问指定索引位置的字符,并对该字符进行读写,语法“字符串名[下标值]”;字符串的下标值(索引值)只能是整数类型,起始值为0。

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

在php中,可以使用substr()函数来读取字符串后几个字符,只需要将该函数的第二个参数设置为负值,第三个参数省略即可;语法为“substr(字符串,-n)”,表示读取从字符串结尾处向前数第n个字符开始,直到字符串结尾的全部字符。

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

方法:1、用“str_replace(" ","其他字符",$str)”语句,可将nbsp符替换为其他字符;2、用“preg_replace("/(\s|\ \;||\xc2\xa0)/","其他字符",$str)”语句。

查找方法:1、用strpos(),语法“strpos("字符串值","查找子串")+1”;2、用stripos(),语法“strpos("字符串值","查找子串")+1”。因为字符串是从0开始计数的,因此两个函数获取的位置需要进行加1处理。


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

PhpStorm 맥 버전
최신(2018.2.1) 전문 PHP 통합 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

에디트플러스 중국어 크랙 버전
작은 크기, 구문 강조, 코드 프롬프트 기능을 지원하지 않음

mPDF
mPDF는 UTF-8로 인코딩된 HTML에서 PDF 파일을 생성할 수 있는 PHP 라이브러리입니다. 원저자인 Ian Back은 자신의 웹 사이트에서 "즉시" PDF 파일을 출력하고 다양한 언어를 처리하기 위해 mPDF를 작성했습니다. HTML2FPDF와 같은 원본 스크립트보다 유니코드 글꼴을 사용할 때 속도가 느리고 더 큰 파일을 생성하지만 CSS 스타일 등을 지원하고 많은 개선 사항이 있습니다. RTL(아랍어, 히브리어), CJK(중국어, 일본어, 한국어)를 포함한 거의 모든 언어를 지원합니다. 중첩된 블록 수준 요소(예: P, DIV)를 지원합니다.
