P粉4516148342023-08-25 11:13:39
Database
这样的类,因为它没有什么用。如果它能为PDO添加一些额外的功能,那么创建一个数据库封装类是有意义的。但是考虑到它当前的代码,最好使用原始的PDO。database.php:
<?php $host = '127.0.0.1'; $db = 'test'; $user = 'root'; $pass = ''; $charset = 'utf8'; $dsn = "mysql:host=$host;dbname=$db;charset=$charset"; $opt = [ \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION, \PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC, \PDO::ATTR_EMULATE_PREPARES => false, ]; $pdo = new \PDO($dsn, $user, $pass, $opt);
user.php
<?php class User { /* Properties */ private $conn; /* Get database access */ public function __construct(\PDO $pdo) { $this->conn = $pdo; } /* List all users */ public function getUsers() { return $this->conn->query("SELECT username, usermail FROM user")->fetchAll(); } }
app.php
include 'database.php'; $user = new User($pdo); $list = $user->getUsers(); foreach($list as $test) { echo $test["username"],"\n"; }
output:
username_foo username_bar username_baz
查看我的(唯一正确的)PDO教程以获取更多PDO的详细信息。