-
Notifications
You must be signed in to change notification settings - Fork 123
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
29 additions
and
24 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,25 +1,30 @@ | ||
<?php | ||
|
||
/** | ||
* 数据库操作类,$pdo属性为静态属性,这样在页面执行周期内, | ||
* 只要经过一次赋值,那么第二次再获取还是首次赋值的内容,这 | ||
* 里就是PDO对象,这样可以确保运行期间只有一个数据库连接对 | ||
* 像,这种是一种简单的单例模式 | ||
* Class Db | ||
*/ | ||
class Db | ||
{ | ||
private static $pdo = null; | ||
|
||
public static function pdo() | ||
{ | ||
if (self::$pdo !== null) { | ||
return self::$pdo; | ||
} | ||
|
||
$dsn = sprintf('mysql:host=%s;dbname=%s', DB_HOST, DB_NAME); | ||
$option = array(PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC); | ||
|
||
return self::$pdo = new PDO($dsn, DB_USER, DB_PASS, $option); | ||
} | ||
<?php | ||
|
||
/** | ||
* 数据库操作类。 | ||
* 其$pdo属性为静态属性,所以在页面执行周期内, | ||
* 只要一次赋值,以后的获取还是首次赋值的内容。 | ||
* 这里就是PDO对象,这样可以确保运行期间只有一个 | ||
* 数据库连接对象,这是一种简单的单例模式 | ||
* Class Db | ||
*/ | ||
class Db | ||
{ | ||
private static $pdo = null; | ||
|
||
public static function pdo() | ||
{ | ||
if (self::$pdo !== null) { | ||
return self::$pdo; | ||
} | ||
|
||
try { | ||
$dsn = sprintf('mysql:host=%s;dbname=%s;charset=utf8', DB_HOST, DB_NAME); | ||
$option = array(PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC); | ||
|
||
return self::$pdo = new PDO($dsn, DB_USER, DB_PASS, $option); | ||
} catch (PDOException $e) { | ||
exit($e->getMessage()); | ||
} | ||
} | ||
} |