PHP实现的一个简单的数据库操作类
实现的功能:
- 在实例化的时候能设置连接字符集
- 在实例化的时候能连接数据库
- 在实例化的时候能选择默认数据库
- 销毁对象时关闭数据库
代码如下:
<?php
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);
}
}