<?php
// 数据库操作类MySQLDB
class MySQLDB {
// 声明属性
private $server;
private $port;
private $username;
private $password;
public $default_db;
private $charset;
public $link;
// 构造函数 当参数较多时,使用数组来作为参数
public function __construct($params = array()) {
echo ‘__construct‘,‘<br />‘;
// 设置连接字符串 通过条件运算符实现默认值的设置
$this->server = isset($params[‘server‘]) ? $params[‘server‘] : ‘127.0.0.1‘;
$this->username = isset($params[‘username‘]) ? $params[‘username‘] : ‘root‘;
$this->password = isset($params[‘password‘]) ? $params[‘password‘] : ‘123456‘;
$this->port = isset($params[‘port‘]) ? $params[‘port‘] : ‘3306‘;
$this->charset = isset($params[‘charset‘]) ? $params[‘charset‘] : ‘utf8‘;
$this->default_db = isset($params[‘default_db‘]) ? $params[‘default_db‘] : ‘mydb‘;
// 实例化对象时连接数据库、选择默认数据库和设置字符集
$this->connect_db();
$this->select_db();
$this->set_charset();
}
// 连接数据库的函数
public function connect_db() {
$this->link = mysql_connect("$this->server:$this->port",$this->username,$this->password);
if (!$this->link) {
echo ‘database connect failure!‘;
die();
}
}
// 选择默认数据库
public function select_db() {
$bool = mysql_select_db($this->default_db,$this->link);
if (!$bool) {
echo ‘Select default_db failure!‘;
die();
}
}
// 设置字符集
public function set_charset() {
$sql = "set names $this->charset";
$bool = mysql_query($sql,$this->link);
if (!bool) {
echo ‘set charset failure‘;
die();
}
}
// 析构函数
public function __destruct() {
echo ‘__destruct‘,‘<br />‘;
mysql_close($this->link);
}
}
原文地址:http://blog.csdn.net/u014044821/article/details/46343083