/*設計模式 「表數據網關」 */
class Gateway
{
protected $connection = null;
public function __construct()
{
$this->connection = new PDO("mysql:host=localhost; dbname=db_users", 'root', '');
}
public function loadAll()
{
$sql = 'SELECT * FROM users';
$rows = $this->connection->query($sql);
return $rows;
}
public function loadById($id)
{
$sql = 'SELECT * FROM users WHERE user_id = ' . (int) $id;
$result = $this->connection->query($sql);
return $result->fetch(PDO::FETCH_ASSOC);
// http://php.net/manual/en/pdostatement.fetch.php //
}
}
/*打印所有的行與列中的 'USER_ID' 僅*/
$gateway = new Gateway();
$users = $gateway->loadAll();
$no = 1;
foreach ($users as $key => $value) {
echo $no . '. ' . $key . ' => ' . $value['user_id'] . '<br />';
$no++;
}
/*打印USER_ID = 1與所有列*/
$user = $gateway->loadById(1);
$no = 1;
foreach ($user as $key => $value) {
echo $no . '. ' . $key . ' => ' . $value . '<br />';
$no++;
}
/*打印USER_ID = 1與柱的電子郵件和密碼」 */
$user = $gateway->loadById(1);
echo $user['email'];
echo $user['password'];
使用'的print_r($用戶);'來查看內容返回 – Martin
它返回一個數組,這是否意味着我剛纔讀它$用戶[‘密碼’]? – PHPDEV
@PHPDEV:是的。確切地說:) –