Home >Backend Development >PHP Tutorial >PDO Common Class Library_PHP Tutorial
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());
}
}
}
?>