이 글은 주로 PHP의 공통 PDO 클래스 라이브러리를 소개하고, 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; } }
요약: 위 내용은 전체 내용입니다. 이 기사가 모든 사람이 도움말을 배우는 데 도움이 되기를 바랍니다.
관련 권장사항:
file_get_contents 함수로 https 주소 가져오기 오류 해결 방법 PHP
위 내용은 PHP PDO 공통 클래스 라이브러리 예제에 대한 자세한 설명의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

PHP는 전자 상거래, 컨텐츠 관리 시스템 및 API 개발에 널리 사용됩니다. 1) 전자 상거래 : 쇼핑 카트 기능 및 지불 처리에 사용됩니다. 2) 컨텐츠 관리 시스템 : 동적 컨텐츠 생성 및 사용자 관리에 사용됩니다. 3) API 개발 : 편안한 API 개발 및 API 보안에 사용됩니다. 성능 최적화 및 모범 사례를 통해 PHP 애플리케이션의 효율성과 유지 보수 성이 향상됩니다.

PHP를 사용하면 대화식 웹 컨텐츠를 쉽게 만들 수 있습니다. 1) HTML을 포함하여 컨텐츠를 동적으로 생성하고 사용자 입력 또는 데이터베이스 데이터를 기반으로 실시간으로 표시합니다. 2) 프로세스 양식 제출 및 동적 출력을 생성하여 htmlspecialchars를 사용하여 XSS를 방지합니다. 3) MySQL을 사용하여 사용자 등록 시스템을 작성하고 Password_Hash 및 전처리 명세서를 사용하여 보안을 향상시킵니다. 이러한 기술을 마스터하면 웹 개발의 효율성이 향상됩니다.

PHP와 Python은 각각 고유 한 장점이 있으며 프로젝트 요구 사항에 따라 선택합니다. 1.PHP는 웹 개발, 특히 웹 사이트의 빠른 개발 및 유지 보수에 적합합니다. 2. Python은 간결한 구문을 가진 데이터 과학, 기계 학습 및 인공 지능에 적합하며 초보자에게 적합합니다.

PHP는 여전히 역동적이며 현대 프로그래밍 분야에서 여전히 중요한 위치를 차지하고 있습니다. 1) PHP의 단순성과 강력한 커뮤니티 지원으로 인해 웹 개발에 널리 사용됩니다. 2) 유연성과 안정성은 웹 양식, 데이터베이스 작업 및 파일 처리를 처리하는 데 탁월합니다. 3) PHP는 지속적으로 발전하고 최적화하며 초보자 및 숙련 된 개발자에게 적합합니다.

PHP는 현대 웹 개발, 특히 컨텐츠 관리 및 전자 상거래 플랫폼에서 중요합니다. 1) PHP는 Laravel 및 Symfony와 같은 풍부한 생태계와 강력한 프레임 워크 지원을 가지고 있습니다. 2) Opcache 및 Nginx를 통해 성능 최적화를 달성 할 수 있습니다. 3) PHP8.0은 성능을 향상시키기 위해 JIT 컴파일러를 소개합니다. 4) 클라우드 네이티브 애플리케이션은 Docker 및 Kubernetes를 통해 배포되어 유연성과 확장 성을 향상시킵니다.

PHP는 특히 빠른 개발 및 동적 컨텐츠를 처리하는 데 웹 개발에 적합하지만 데이터 과학 및 엔터프라이즈 수준의 애플리케이션에는 적합하지 않습니다. Python과 비교할 때 PHP는 웹 개발에 더 많은 장점이 있지만 데이터 과학 분야에서는 Python만큼 좋지 않습니다. Java와 비교할 때 PHP는 엔터프라이즈 레벨 애플리케이션에서 더 나빠지지만 웹 개발에서는 더 유연합니다. JavaScript와 비교할 때 PHP는 백엔드 개발에서 더 간결하지만 프론트 엔드 개발에서는 JavaScript만큼 좋지 않습니다.

PHP와 Python은 각각 고유 한 장점이 있으며 다양한 시나리오에 적합합니다. 1.PHP는 웹 개발에 적합하며 내장 웹 서버 및 풍부한 기능 라이브러리를 제공합니다. 2. Python은 간결한 구문과 강력한 표준 라이브러리가있는 데이터 과학 및 기계 학습에 적합합니다. 선택할 때 프로젝트 요구 사항에 따라 결정해야합니다.

PHP는 서버 측에서 널리 사용되는 스크립팅 언어이며 특히 웹 개발에 적합합니다. 1.PHP는 HTML을 포함하고 HTTP 요청 및 응답을 처리 할 수 있으며 다양한 데이터베이스를 지원할 수 있습니다. 2.PHP는 강력한 커뮤니티 지원 및 오픈 소스 리소스를 통해 동적 웹 컨텐츠, 프로세스 양식 데이터, 액세스 데이터베이스 등을 생성하는 데 사용됩니다. 3. PHP는 해석 된 언어이며, 실행 프로세스에는 어휘 분석, 문법 분석, 편집 및 실행이 포함됩니다. 4. PHP는 사용자 등록 시스템과 같은 고급 응용 프로그램을 위해 MySQL과 결합 할 수 있습니다. 5. PHP를 디버깅 할 때 error_reporting () 및 var_dump ()와 같은 함수를 사용할 수 있습니다. 6. 캐싱 메커니즘을 사용하여 PHP 코드를 최적화하고 데이터베이스 쿼리를 최적화하며 내장 기능을 사용하십시오. 7


핫 AI 도구

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

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

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

Clothoff.io
AI 옷 제거제

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

인기 기사

뜨거운 도구

SublimeText3 Linux 새 버전
SublimeText3 Linux 최신 버전

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

ZendStudio 13.5.1 맥
강력한 PHP 통합 개발 환경

Eclipse용 SAP NetWeaver 서버 어댑터
Eclipse를 SAP NetWeaver 애플리케이션 서버와 통합합니다.

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