0

我正在编写一个简单的 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);
    }

}
4

1 回答 1

0

Assuming you want to bind parameters.

You don't actually need to bind them as PDO has a very handy feature of feeding execute() with array of values.

Though after taking a second look at this class I see not much point in it. as it giving you no benefit over PDO...

As you can have the same workflow with raw 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();
    }

}

used as follows

$db = new Database();
$stmt = $db->prepare("SELECT id FROM users WHERE email = ?");
$row =  $db->single($stmt, $array($email));

于 2013-06-27T20:02:04.257 回答