Mysqli Prepared Statement Fetch Assoc

时间:2013-03-24 12:52:39

标签: php mysqli

我正在为我的网站制作一个mysqli课程,但我被困了。

这是我的班级:

class Database  {

    private $mysqli = '';
    private $params = '';
    private $result = '';

    function Database($hostname, $username, $password, $database) {
        $this->mysqli = new mysqli($hostname, $username, $password, $database);

        if ($this->mysqli->connect_errno) {
            printf('Error #%s -> %s', $this->mysqli->connect_errno, $this->mysqli->connect_error);
            exit;
        }
    }

    public function setQuery($query) {
        $this->result = $this->mysqli->prepare($query); 
        $this->params = array();
        return $this;
    }

    public function setParam($type, $value) {
        $this->params[$type] = $value;

        return $this;
    }

    public function execute() {
        $params = $this->params;

        foreach ($params as $key => $value) {
            $this->result->bind_param($key, $value);
        }

        $user = $this->result->result_metadata()->fetch_assoc();
        echo $user['username'];
    }


}

我正在使用:

Core::$database->setQuery('SELECT * FROM habbo_characters WHERE id = ?')->setParam('i', 1)->execute();

但我没有输出/空字符串作为输出。我做错了什么? setParam函数正常工作,不是这样。 它包含id为1的用户(sql)。

1 个答案:

答案 0 :(得分:-1)

使用PDO:

<?php
/* Execute a prepared statement by passing an array of values */
$sql = 'SELECT name, colour, calories
    FROM fruit
    WHERE calories < :calories AND colour = :colour';
$sth = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$sth->execute(array(':calories' => 150, ':colour' => 'red'));
$red = $sth->fetchAll();
$sth->execute(array(':calories' => 175, ':colour' => 'yellow'));
$yellow = $sth->fetchAll();
?>

可在此处找到更多示例:http://php.net/manual/de/pdo.prepare.php