1。文件名 Mysql.php
<?php
define("PAGE_SIZE",10);
define("IP_WHITE",1);
define("IP_BLACK",0);
define("WORD_CN",1);
define("WORD_EN",0);
class Mysql
{
private $server="127.0.0.1";//服务器ip
private $user = "telnet"; //用户名
private $password = "a"; //密码
private $database="telnet"; //所用数据库名
private $link = null;
private $result=null;
//构造方法初始化,连接数据库
private function __construct()
{
$link = mysqli_init();
$this->link = mysqli_connect($this->server,$this->user,$this->password,$this->database) or die('Could not connect: ' . mysql_error());
}
//返回一个实例
public static function getInstance()
{
return new self();
}
//查询操作使用,返回查询内容
public function query($sql)
{
$this->result = @mysqli_query($this->link,$sql);
$list = new ArrayIterator();
while(($row=@mysqli_fetch_array($this->result ,MYSQL_ASSOC))!=null)
{
$list->append($row);
}
return $list;
}
//修改,删除,添加抄作使用,返回操作结果
public function execute($sql)
{
try{
@mysqli_query($this->link,$sql);
@mysqli_commit();
}catch (Exception $e){
return false;
}
return true;
}
//分页使用,返回页数
public function page($sql)
{
$list=$this->query($sql);
$all = $list[0]['count(*)'];
if($all == 0) return 1;
else return (int)(($all-1)/PAGE_SIZE+1);
}
//析构函数,关闭连接
public function close()
{
if($this->result != null)
{
mysqli_free_result($this->result);
}
if($this->link != null)
{
mysqli_close($this->link);
}
}
}
?>
2. UserService.php
<?php
Class UserService
{
private $mysql;
//连接数据库
public function __construct()
{
$this->mysql = Mysql::getInstance();
}
//通过id删除用户
public function deleteById($id)
{
$sql = "delete from user where id=$id";
//使用mysql.php的execute方法
if($this->mysql->execute($sql) == 1)return true;
else return false;
}
//通过查询id,查询用户
public function selectById($id)
{
$sql = "select * from user where id=$id";
return $this->mysql->query($sql);
}
//按条件查询用户,最后一个参数为页数
public function select($name,$authority,$page)
{
$from = ($page-1) * PAGE_SIZE;
$count = PAGE_SIZE;
if($name==""||$name==null)
{
$name = "%";
}
if($authority==""||$authority==null)
{
$authority = "%";
}
$sql = "select * from user where name like '$name%' and authority like '$authority' limit $from,$count";
return $this->mysql->query($sql);
}
//与select函数参数相同,返回此条件下的总的页数
public function page($name,$authority)
{
if($name==""||$name==null)
{
$name = "%";
}
if($authority==""||$authority==null)
{
$authority = "%";
}
$sql="select count(*) from user where name like '$name%' and authority like '$authority'";
return $this->mysql->page($sql);
}
//关闭连接
public function __destruct()
{
$this->mysql->close();
}
}
// $user->close();
?>