-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathDao.class.php
executable file
·73 lines (60 loc) · 1.73 KB
/
Dao.class.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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
<?php
/**
* 数据访问对象模式
* 解决问题:如何创建透明访问任何数据源的对象(重复和数据源抽象化)
*/
abstract class baseDAO
{
private $__connection;
public function __construct()
{
$this->__connectToDB(DB_USER, DB_PASS, DB_HOST, DB_DATABASE);
}
private function __connectToDB($user, $pass, $host, $database)
{
$this->__connection = mysql_connect($host, $user, $pass);
mysql_select_db($database, $this->__connection);
}
public function fetch($value, $key = NULL)
{
if(is_null($key))
{
$key = $this->_primaryKey;
}
$sql = "select * from {$this->_tableName} where {$key}='{$value}'";
$results = mysql_query($sql, $this->__connection);
$rows = array();
while ($result = mysql_fetch_array($results))
{
$rows[] = $result;
}
return $rows;
}
public function update($keyedArray)
{
$sql = "update {$this->_tableName} set ";
foreach ($keyedArray as $column=>$value)
{
$updates[] = "{$column} = '{$value}' ";
}
$sql .= implode(",",$updates);
$sql .= "where {$this->_primaryKey}='{$keyedArray[$this->_primaryKey]}'";
mysql_query($sql, $this->__connection);
}
}
class userDAO extends baseDAO
{
protected $_tableName = "userTable";
protected $_primaryKey = "id";
public function getUserByFirstName($name)
{
$result = $this->fetch($name, 'firstName');
return $result;
}
}
$user = new userDAO();
$id = 1;
$userInfo = $user->fetch($id);
$updates = array('id'=>1, 'firstName'=>'arlon');
$user->update($updates);
$all = $user->getUserByFirstName('arlon');