許桔
<?php
require("db_connection.php");
require("model/model.php");
//判斷網址帶來的GET
if( isset( $_GET['action'] ) ){
switch($_GET['action']){
case 'show': //顯示資料
break;
case 'insert' : //新增資料
break;
....
default : //找不到頁面!
require("view/error.php");
}
}else{
require("view/error.php");
}
....
switch($_GET['action']){
case 'show': //顯示資料
$prepareSQL = "SELECT * FROM student";
$executeSQL = array();
$sql = $model->getDataSQL($prepareSQL, $executeSQL);
require("view/show.php");
break;
.....
default : //找不到頁面!
require("view/error.php");
}
<form action="insert.php" method="POST">
<form action="?action=insert" method="POST">
class model{
//告知資料庫在哪
function __construct(PDO $dbh){
$this->dbh = $dbh;
}
function getDataSQL($prepareSQL, $executeSQL) { //顯示資料
$dbh = $this->dbh;
$sql = $dbh->prepare($prepareSQL);
$sql->execute($executeSQL);
return $sql->fetchAll();
}
.......
用Class把Model包起來
if(isset($_GET['action'])){
$model = new model($dbh);
switch($_GET['action']){
case 'show': //顯示資料
$prepareSQL = "SELECT * FROM student";
$executeSQL = array();
$sql = $model->getDataSQL($prepareSQL, $executeSQL);
require("view/show.php");
break;
.....
引入model統一呼叫db,避免各別重複呼叫db物件