0%

[技能檢定]題組一 步驟3 建立共用函式檔

我們使用到了物件導向來宣告了一個類別DB,這個類別足夠可以處理題組一大多數的功能,為了更好的在解題是可以快速的應用到這個類別的功能,因為我們建立一個共用函式檔,將整個題組都會用到的變數及函式都集中放到這個檔案中,再透過include的方式將檔案匯入到最主要的index.php及back.php,由於這兩個檔案會再include各個子頁面,因此相當於所有的頁面都可以使用到這個共用函式檔的變數。

同時我們也把一些好用的小函式集中放在一個檔案中,透過include的方式讓各個頁面都能使用到這些類別及函式。

建立題組專用共用函式檔

/db.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
session_start();       //啟用session功能
date_default_timezone_set("Asia/Taipei"); //設定網站的時區為亞洲台北

//簡易的自訂函式
/**
* 用來顯示陣列內容-除錯時使用
*/
function dd($array){
echo "<pre>";
print_r($array);
echo "</pre>";
}

/**
* 簡化header('location:')的使用
* 將請求導向其他檔案或頁面
*/
function to($url){
header("location:".$url);
}

/**
* 用來處理較複雜的sql語句,比如子查詢或聯表查詢
* 預設回傳的資料是2維陣列
*/
function q($sql){
$pdo=new PDO("mysql:host=localhost;charset=utf8;dbname={your db name}",'root','');
return $pdo->query($sql)->fetchAll(PDO::FETCH_ASSOC);
}

//宣告各個類別的物件變數
$Title=new DB('titles');
$Total=new DB('total');
$Bottom=new DB('bottom');
$Ad=new DB('ad');
$Mvim=new DB('mvim');
$Image=new DB('image');
$News=new DB('news');
$Admin=new DB('admin');
$Menu=new DB('menu');

接著將這個檔案引入到 index.phpbackend.php 中:

/index.php

1
2
3
4
5
<?php include_once "db.php";?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

/back.php

1
2
3
4
5
<?php include_once "db.php";?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">