为什么我的foreach循环不显示我的mysql数据?

时间:2016-12-02 19:54:00

标签: php mysql oop pdo

我正在尝试扩展this tutorial on youtube的功能,我遇到了一些问题。以下是我目前正在努力解决的特定代码块:

public function listProjects() {
    $projects = DB::getInstance()->get('projects', array('projectStatus', '=', 'active'));
    if($projects->count()) {
        echo 'This query senses rows, but returns data it does not';
        foreach($projects as $project) {
            echo $project->projectName;
        }
    }
}

这是我的“Project”类的一个方法,它使用了DB类中的方法,其中包含相关代码:

private function __construct() {
    try {
        $this->_pdo = new PDO('mysql:host=' . Config::get('mysql/host') . ';dbname=' . Config::get('mysql/db'), Config::get('mysql/username'),  Config::get('mysql/password')); 
    } catch(PDOException $e){
        die($e->getMessage());
    }
}


public static function getInstance() {
    if(!isset(self::$_instance)){
        self::$_instance = new DB();
    }
    return self::$_instance;
}


public function query($sql, $params = array()){
    $this->_error = false;
    if($this->_query = $this->_pdo->prepare($sql)) {
        $x = 1;
        if(count($params)) {
            foreach($params as $param) {
                $this->_query->bindValue($x, $param);
                $x++;
            }
        }
        if($this->_query->execute()) {
            $this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
            $this->_count = $this->_query->rowCount();
        } else {
            $this->_error = true;
        }
    }
    return $this; 
}


public function action($action, $table, $where = array()) {
    if(count($where) === 3) {
        $operators = array('=', '>', '<', '>=', '<=');

        $field = $where[0];
        $operator = $where[1];
        $value = $where[2];

        if(in_array($operator, $operators)) {
            $sql = "{$action} FROM {$table} WHERE {$field} {$operator} ?";
            if(!$this->query($sql, array($value))->error()) {
                return $this;
            }
        }

    } return $this;

}


public function get($table, $where) {
    return $this->action('SELECT *', $table, $where);

}

所以在我的index.php中,我写了这段代码:

$projectList = new Project;
$projectList->listProjects();

尝试检索存储在数据库中的所有“项目”。我把“这个查询检测行,但返回它没有的数据”回显以确定行是否被计数,它们是,因为该语句被回显,但我的foreach语句无法正常工作。我试图访问的项目表中的字段是projectName。我最终希望显示所有相关的项目信息,但我确信一旦我从数据库中显示任何内容,我就能弄明白。

1 个答案:

答案 0 :(得分:-2)

此:

 foreach($projects as $project) {
            echo $project->projectName;
        }

应该是:

 foreach($projects as $project) {
                echo $projects->projectName;
            }