我正在编写一个简单的PDO数据库类,我想自动绑定结果,但我不确定我应该如何处理它,任何帮助都会很棒!
我真的希望这个课程尽可能简单,所以如果你知道其他任何方法我可以简化这个课程,这将很棒。
这是我的数据库类:
class Database {
private $connect;
private $query;
private $stmt;
/**
* @ Connect to the database and set PDO error mode
*/
public function __construct() {
try {
$this->connect = new PDO("mysql:host=localhost;dbname=blog", "root", "root");
$this->connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $error) {
echo "ERROR: " . $error->getMessage();
}
}
/**
* @ Perpare the database query
*/
public function query($query) {
$this->stmt = $this->connect->prepare($query);
if ($action == 'insert' || $action == 'update') {
reset ($array);
}
}
/**
* @ Bind the results
*
*/
public function bind() {
// THIS IS WHERE I NEED HELP
}
/**
* @ Execute the query
*/
public function execute() {
return $this->stmt->execute();
}
/**
* @ Return a set of results
*/
public function results() {
$this->execute();
return $this->stmt->fetchAll(PDO::FETCH_ASSOC);
}
/**
* @ Return a single result
*/
public function single() {
$this->execute();
return $this->stmt->fetch(PDO::FETCH_ASSOC);
}
}
答案 0 :(得分:0)
假设您要绑定参数。
您实际上不需要绑定它们,因为PDO有一个非常方便的功能,即使用值数组提供execute()
。
虽然在第二次看这个课程之后,我看到的并不多。因为它不会给你带来超过PDO的好处......
因为您可以使用原始PDO具有相同的工作流程
$db = new PDO(...);
$stmt = $db->prepare("SELECT id FROM users WHERE email = ?");
$stmt->execute($array($email));
$row = $stmt->fetch();
class Database {
private $connect;
private $query;
private $stmt;
public function __construct() {
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
$dsn = "mysql:host=localhost;dbname=blog";
$this->connect = new PDO(, "root", "root". $opt);
$this->connect->setAttribute();
}
public function prepare($query) {
return $this->connect->prepare($query);
}
public function execute($stmt, $params) {
return $stmt->execute($params);
}
public function single($stmt, $params) {
$stmt->execute($params);
return $stmt->fetch();
}
}
使用如下
$db = new Database();
$stmt = $db->prepare("SELECT id FROM users WHERE email = ?");
$row = $db->single($stmt, $array($email));