面向對象筆記 單例的數據庫工具類

1 單例的數據庫工具類(./libs/Db.class.php)

//創建單例的數據庫類
class Db{
    //私有的靜態的保存對象的屬性
    private static $obj= NULL;

    //私有的數據庫配置信息
    private $db_host;//主機名
    private $db_user;//用戶名
    private $db_pass;//密碼
    private $db_name;//數據庫名
    private $charset;//字符集

    //私有的構造方法,阻止類外new對象
    private function __construct($config){
        $this->db_host=$config['db_host'];
        $this->db_user=$config['db_user'];
        $this->db_pass=$config['db_pass'];
        $this->db_name=$config['db_name'];
        $this->charset=$config['charset'];
        $this->connectDb();//鏈接mysql服務器
        $this->selectDb();//選擇數據庫
        $this->setCharset();//設置字符集
    }
    //私有的克隆方法,阻止類外new對象
    private function __clone(){}
    //公有的靜態的創建對象的方法
    public static function getInstance($config){
        //判斷當前對象是否存在
        if(!self::$obj instanceof self){
            //如果對象不存在,則創建它
            self::$obj=new self($config);
        }
        //返回當前對象
        return self::$obj;
    }

    //私有的連接MySQL服務器的方法
    private function connectDb(){
        if(!@mysql_connect($this->db_host,$this->db_user,$this->db_pass)){
            die("PHP連接MySQL服務器出錯!");
        }
    }
    //私有的選擇數據庫的方法
    private function selectDb(){
        if(!mysql_select_db($this->db_name)){
            die("選擇數據庫{$this->db_name}失敗!");
        }
    }
    //私有的設置字符集
    private function setCharset(){
        $this->exec("set names {$this->charset}");
    }

    //公共的執行SQL語句的方法:insert、update、delete、set、create、drop
    public function exec($sql){
        //將SQL語句轉成全小寫   $sql="select $ from student";
        $sql=strtolower($sql);
        //判斷SQL語句是否select語句
        if(substr($sql,0,6)=='select'){
            die("該方法不能執行select語句");
        }
        //如果是非select語句,則正常執行,並返回布爾值
        return mysql_query($sql);
    }

    //私有的執行SQL語句的方法:select
    private function query($sql){
       //將SQL語句轉成全小寫   $sql="select $ from student";
        $sql=strtolower($sql);
        //判斷SQL語句是否select語句
        if(substr($sql,0,6)!='select'){
            die("該方法不能執行非select語句");
        }
        //如果是select語句,則正常執行,並返回結果集
        return mysql_query($sql);
    }

    //公共的獲取單行記錄的方法(一維數組)
    public function fetchOne($sql,$type=3){
        //執行SQL語句並返回結果集
        $result=$this->query($sql);

        //定義返回數組的類型
        $types=array(
            1=>MYSQL_NUM,
            2=>MYSQL_BOTH,
            3=>MYSQL_ASSOC
        );
        //返回一條記錄
        return mysql_fetch_array($result,$types[$type]);
    }

    //公共的獲取多行記錄的方法(二維數組)
    public function fetchAll($sql,$type=3){
        //執行SQL語句並返回結果集
        $result=$this->query($sql);

        //定義返回數組的類型
        $types=array(
            1=>MYSQL_NUM,
            2=>MYSQL_BOTH,
            3=>MYSQL_ASSOC
        );
        //循環從結果集中取出所以記錄,並存入新數組中
        while ($row=mysql_fetch_array($result,$types[$type])){
            $arrs[]=$row;
        }
        //返回二維數組
        return $arrs;
    }

    //公共的獲取記錄數
    public function rowCount($sql){
        //執行SQL語句並返回結果集
        $result=$this->query($sql);
        //返回記錄數
        return mysql_num_rows($result);
    }
}

2 連接數據庫的公共文件(./conn.php)

//(1)類的自動加載
spl_autoload_register('autoload');
function autoload($className){
    //構建類文件的真實路徑
    $fileName="./libs/$className.class.php";
    //如果類文件存在,則包含
    if(file_exists($fileName))
        require_once ($fileName);
}

//(2)創建數據庫類的對象
$arr=array(
    'db_host'=>'localhost',
    'db_user'=>'root',
    'db_pass'=>'',
    'db_name'=>'newdb3',
    'charset'=>'utf8'
);
$db=Db::getInstance($arr);
var_dump($db);

3 顯示學生信息列表

<?php
header("content-type:text/html;charset=utf-8");
//包含鏈接數據庫的文件
require_once ("./coon.php");
//獲取多行數據
$sql="select * from student order by id";
$arrs =$db->fetchAll($sql);
//獲取記錄數
$records=$db->rowCount($sql);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div style="text-align: center;padding-bottom: 10px;">
    <h2>學生信息管理中心</h2>
    <a href="./add.php">添加學生</a><font color="red"><?php echo $records;?></font>個學生
</div>
<table width="800" border="1" bordercolor="#ccc" rules="all" align="center" cellpadding="5">
    <tr bgcolor="#f0f0f0">
        <th>編號</th>
        <th>姓名</th>
        <th>性別</th>
        <th>年齡</th>
        <th>學歷</th>
        <th>工資</th>
        <th>獎金</th>
        <th>籍貫</th>
        <th>操作選項</th>
    </tr>
    <?php
    //循環二維數組
    foreach ($arrs as $arr){?>
    <tr align="center">
        <td><?php echo $arr['id']?></td>
        <td><?php echo $arr['name']?></td>
        <td><?php echo $arr['sex']?></td>
        <td><?php echo $arr['age']?></td>
        <td><?php echo $arr['edu']?></td>
        <td><?php echo $arr['salary']?></td>
        <td><?php echo $arr['bonus']?></td>
        <td><?php echo $arr['city']?></td>
        <td>
            <a href="./edit.php?id=<?php echo $arr['id']?>">修改</a>
            <a href="javascript:void (0)" onclick="confirmDel(<?php echo $arr['id']?>>刪除</a>
        </td>
    </tr>
    <?php }?>
</table>
</body>
</html>

4 刪除一條記錄(./delete.php)

4.1 學生管理首頁(list.php)

在這裏插入圖片描述

4.2 delete.php

header("content-type:text/html;charset=utf-8");

//包含連接數據庫的公共文件
require_once ("./coon.php");
//獲取地址欄傳遞的id
$id=$_GET['id'];
//構建刪除的SQL語句
$sql="DELETE FROM student WHERE id=$id";
//執行SQL語句
if($db->exec($sql)){
    //輸出提示,3秒鐘後,調回列表頁
    echo "<h2>id={$id}的學生信息刪除成功!</h2>";
    header("refresh:3;url=./list.php");
    die();
}

5 添加一條記錄(add.php)

5.1 添加的表單代碼

在這裏插入圖片描述

5.2處理表單提交的數據

<?php
header("content-type:text/html;charset=utf-8");
//(1)包含連接數據庫的公共文件
require_once ("./coon.php");
//(2)判斷表單是否提交
if (isset($_POST['ac']) && $_POST['ac']=='add'){
    //獲取表單提交值
    foreach ($_POST as $k=>$v){
        $$k=$v;
    }
    //構建插入的SQL語句
    $sql="INSERT INTO student VALUES(NULL ,'$name','$sex',$age,'$edu',$salary,$bonus,'$city')";
    //執行SQL語句
    if($db->exec($sql)){
        echo"<h2>學生信息添加成功!</h2>";
        header("refresh:3;url=./list.php");
        die();
    }
}
?>

6 創建一個分頁類(./libs/Pager.class.php)

<?php
//定義最終的分頁類
final class Pager{
    //私有的成員屬性
    private $curPage;//當前頁
    private $totalPage;//總頁數
    public function __construct($curPage,$totalPage){
        $this->curPage=$curPage;
        $this->totalPage=$totalPage;
    }
    //公共的分頁的方法
    public function fenPagers(){
        //計算循環的開始頁和結束頁
        $start=$this->curPage-5;
        $end=$this->curPage+4;
        if($this->curPage<6){
            $start=1;
            $end=$end+6-$this->curPage;
        }
        if ($end>$this->totalPage){
            $start=$this->totalPage-10+1;
            $end=$this->totalPage;
        }
        if($this->totalPage<=10){
            $start=1;
            $end=$this->totalPage;
        }

        //實現上一頁
        $prev=$this->curPage-1<=1?1:$this->curPage-1;
        echo "<a href=?curPage=$prev'>&laquo;</a>";

        //循環顯示所有的頁碼
        for($i=$start;$i<=$end;$i++){
            if($i==$this->curPage){
                echo"<span class='current'>$i</span>";
            }else{
                echo "<a href='?curPage=$i'>$i</a>";
            }
        }

        //實現下一頁
        $next=$this->curPage+1>=$this->totalPage?$this->totalPage:$this->curPage+1;
        echo "<a href='?curPage=$next'>&raquo;</a>";

    }
}

7 列表頁分頁代碼

<?php
header("content-type:text/html;charset=utf-8");
//(1)包含鏈接數據庫的文件
require_once ("./coon.php");
//(2)分頁參數
$pageSize=5;
$curPage=isset($_GET['curPage'])?$_GET['curPage']:1;
$startRow=($curPage-1)*$pageSize;

//(3)獲取多行數據
$sql="SELECT * FROM student";
$records =$db->rowCount($sql);
$totalPage=ceil($records/$pageSize);

//(4)獲取記錄數
$sql.=" ORDER BY id LIMIT {$startRow},{$pageSize}";
$arrs=$db->fetchAll($sql);
		<tr>
            <td colspan="9" align="center" class="pagelist">
                    <?php
                    //創建分頁類對象
                    $pageObj=new Pager($curPage,$totalPage);
                    $pageObj->fenPagers();
                    ?>
            </td>
        </tr>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章