代码
<?php
header("content-type:text/html;charset=utf-8");
final class DB
{
private $charset = "utf8";
private $link = NULL;
private static $instance = NULL;
//初始化
private function __construct($hostfield, $userfield, $password, $datebase)
{
$this->link = mysqli_connect($hostfield, $userfield, $password, $datebase);
if (!$this->link) {
die("连接失败: " . mysqli_connect_error());
}
mysqli_query($this->link, "SET fieldS " . $this->charset);
return $this->link;
}
//防止克隆
private function __clone()
{
}
//静态公共接口
public static function getInstance($hostfield, $userfield, $password, $datebase)
{
if (!self::$instance instanceof self) {
self::$instance = new DB($hostfield, $userfield, $password, $datebase);
}
return self::$instance;
}
/*
*describe:执行原生sql
*/
public function query($sql)
{
if (mysqli_query($this->link, $sql)) {
return mysqli_affected_rows($this->link);
} else {
echo "error:" . $sql . "<br/>" . mysqli_error($this->link);
}
}
}
/**
* 测试
*/
$class = DB::getInstance("localhost", "root", "root", "test");
var_dump($class->query("select * from users"));
运行截图