在FleaPHP这些开发框架中已经对数据库操作,分页作了很好的封装.功能强大且易于使用.不过自己写类对于理解OOP总不是一件坏事.
对PHP面向对象编程方面还是新手 所以这个类还有很多不完善的地方.功能也太简单
没有文档,没有注释,就我自己能看懂.以后完善后再发布正式版本.
代码如下:
class Datebase
{
function __construct()
{
require_once("db_config.php"); //包含配置文件
$this->conn=mysql_pconnect($host,$username,$password);
$this->datebase=$datebase;
echo '数据库连接成功<BR>';
}
function errorOutput($error)
{
echo $error.'<BR>';
die ('程序运行已停止');
}
function sqlInput($sql)
{
if(empty($sql))
$this->error('sql语句未定义');
$my_db=mysql_select_db($this->datebase,$this->conn);
if(!$my_db)
$this->errorOutput('数据库选择错误');
$result=mysql_query($sql,$this->conn);
if(!$result)
$this->errorOutput('SQL查询错误');
$info=mysql_fetch_array($result);
return $result;
}
function pages($sql,$pagesize,$showpage=1)
{
$result=$this->sqlInput($sql);
$numRows=mysql_num_rows($result);
$allpages=intval($numRows/$pagesize);
if ($numRows%$pagesize)
$allpages++;
if($showpage<1||$showpage>$allpages)
$this->errorOutput('非法的页码请求');
$offset=$pagesize*($showpage - 1);
$pagesql=$sql.' limit '. $offset.','.$pagesize;
$pageresult=$this->sqlInput($pagesql);
if(!$result)
$this->errorOutput('分页查询错误');
return $result;
}
}
$sql='select * from news';
$a= new Datebase();
$result=$a->sqlInput($sql);
$resultpage=$a->pages($sql,12,1);
另外还有一个数据库配置文件 db_config.php
$datebase='mysql';
$username='root';
$password=' ';
$host='localhost';