Home > Backend Development > PHP Tutorial > PDO Common Class Library_PHP Tutorial

PDO Common Class Library_PHP Tutorial

WBOY
Release: 2016-07-13 17:47:57
Original
986 people have browsed it

1. Db.class.php

// Connect to database
class Db {
static public function getDB() {
         try {
                $pdo = new PDO(DB_DSN, DB_USER, DB_PWD);
                  $pdo->setAttribute(PDO::ATTR_PERSISTENT, true); // Set the database connection to a persistent connection
                 $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Setup throws an error
                  $pdo->setAttribute(PDO::ATTR_ORACLE_NULLS, true); // Set when the string is empty, it is converted to NULL in SQL
                  $pdo->query('SET NAMES utf8'); // Set database encoding
           } catch (PDOException $e) {
                       exit('Database connection error, error message:'. $e->getMessage());
         } 
          return $pdo;
}  
}
?>
//Connect to database
class Db {
static public function getDB() {
try {
$pdo = new PDO(DB_DSN, DB_USER, DB_PWD);
$pdo->setAttribute(PDO::ATTR_PERSISTENT, true); //Set the database connection as a persistent connection
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Set throw error
$pdo->setAttribute(PDO::ATTR_ORACLE_NULLS, true); //Set when the string is empty, it is converted to SQL NULL
$pdo->query('SET NAMES utf8'); // Set database encoding
} catch (PDOException $e) {
exit('Database connection error, error message:'. $e->getMessage());
}
return $pdo;
}
}
?>
2. Model.class.php


//Operation SQL
class Model {
/**
* SQL addition, deletion and modification operations, return the number of affected rows
* @param string $sql
* @return int
​​*/
Public function aud($sql) {
         try {
               $pdo = Db::getDB();
$row = $pdo->exec($sql);
           } catch (PDOException $e) {
exit($e->getMessage());
         } 
         return $row;
}  
       
/**
* Return all data, return PDOStatement object
* @param string $sql
* @return PDOStatement
​​*/
Public function getAll($sql) {
         try {
               $pdo = Db::getDB();
                 $result = $pdo->query($sql);
               return $result;
           } catch (PDOException $e) {
exit($e->getMessage());
         } 
}  
}
?>


Excerpted from Lee.’s column

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/478464.htmlTechArticle1、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); /...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template