設數據表Users:
則在PHP中可以定義一個User類和基類DataObject,使得訪問數據表可以用下面的方法:
<?php
include_once('conn.php');
include_once('DataObject.php');
include_once('User.php');
// 添加一個新用戶
$user = new User();
$user->name = 'oct1158';
$user->password = '789012';
$user->useFunction('birthday', 'NOW()');
echo 'Field birthday uses MySQL Function: ', $user->birthday, '<br>';
if ($user->insert()) {
echo 'New User ID: ', $user->id, '<br>';
// 更新用戶信息
$user->password = '112233';
$user->update();
} else {
echo 'INSERT Failed<br>';
}
// 獲取一個用戶
$sql = 'SELECT * FROM Users WHERE UserName = ?';
$stmt = $dbh->prepare($sql);
$stmt->execute(array('admin'));
$admin_user = $stmt->fetchObject('User');
echo 'Admin ID is ', $admin_user->id, '.<br>';
echo 'Admin Birthday is ', $admin_user->birthday, '.<br>';
$users = User::GetAll();
echo '<br>';
echo $users[0]->name, ', ', $users[0]->birthday, '<br>';
echo $users[1]->name, ', ', $users[1]->birthday, '<br>';
echo $users[2]->name, ', ', $users[2]->birthday, '<br>';
echo '<br>';
// 刪除一個用戶
$user = new User();
$user->insert();
$user->delete();