mysql 自己写数据库,自己写了一个简单的mysql数据库连接类
直接上代碼吧,有時間在維護下
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}
";
}
if($this->mysqli->errno) {
$result.= "錯誤代號:{$this->mysqli->errno}
";
}
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 自己写数据库,自己写了一个简单的mysql数据库连接类的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 用PHP删除一条记录mysql,php
- 下一篇: matlab 三角形隶属函数,在MATL