自己写了一个简单的mysql数据库连接类

时间:2022-12-11 16:06:21

直接上代码吧,有时间在维护下

class DB {
private $host; //主机
private $username; //用户名
private $password; //密码
private $dbName; //数据库名称
private $port; //数据库端口
private $socket; //套接字
private $mysqli; //mysqli对象
private $charset; //字符集
private $lastSql; //最后执行的sql

public function __construct($array=[])
{
$this->charset = isset($array['charset']) ? $array['charset'] : 'utf8';
$this->connect($array);
$this->mysqlConnect();
}

public function connect($array=[])
{
$this->host = isset($array['host']) ? $array['host'] : '127.0.0.1';
$this->username = isset($array['username']) ? $array['username'] : 'root';
$this->password = isset($array['password']) ? $array['password'] : 'root';
$this->dbName = isset($array['dbName']) ? $array['dbName'] : '';
$this->port = isset($array['port']) ? $array['port'] : 3306;
$this->socket = isset($array['socket']) ? $array['socket'] : '';
}

private function mysqlConnect()
{
$this->mysqli = new mysqli($this->host,$this->username,$this->password,$this->dbName,$this->port);
}


public function query($sql)
{
$this->lastSql = $sql;
$result = $this->mysqli->query($this->lastSql);
if($result === false) {
$this->error();
}
return $result;
}

public function Charset($charset='')
{
$this->charset = $charset ? $charset: $this->charset;

$this->execute("set names {$this->charset}");
}


public function execute($sql)
{
$this->query($sql);
return true;

}

public function select($sql)
{
$result = $this->query($sql);
return $result->fetch_all(MYSQLI_ASSOC);

}

public function getLastSql()
{
return $this->lastSql;
}

public function error()
{
$result = '';
if($this->mysqli->error) {
$result.= "错误提示:{$this->mysqli->error}<br />";
}

if($this->mysqli->errno) {
$result.= "错误代号:{$this->mysqli->errno}<br />";
}
if(!empty($result)){
$result.="错误的sql语句:{$this->lastSql}";
}

if(!empty($result)) {
exit($result);
} else {
exit('没有错误');
}
}

}


本地试试:

$db = new DB(['dbName'=>'test']);

var_dump($db->select('select * from test limit 0,5'));

var_dump($db->select('select name,time from test where id in(1,5)'));

echo $db->getLastSql();

运行结果如图所示:

自己写了一个简单的mysql数据库连接类