无法从PDO查询中获取数组

时间:2012-06-14 15:56:38

标签: php mysql pdo

我正在尝试使用pdo从SQL查询中获取数组,我发送给它的方法是例如$connection->selectFrom('Person',array(1,2));

当我尝试获得结果时,它返回一个空数组,这是我的代码:

public function selectFrom($table,$indexes){
    try{
        $pdo=$this->getPdo();
        // HERE I GET ALL THE COLUMN NAMES FROM THE TABLE I RECEIVE
        $columns = $this->getColumnNames($table);
        $finals = array();
        // IN THIS CICLE I GET THE COLUMNS THAT MATCH THE INDEXES I RECEIVE
        for($i=0;$i<count($indexes);$i++){
            $finals[$i] = $columns[$indexes[$i]];
        }
        // FROM HERE I GET THE QUERY STATEMENT WICH IS SELECT column1,column2 from $table 
        $query = $this->getSelectSQL($table, $finals);

        // ALL OF THE ABOVE WORKS BUT HERE IT STOPS WORKING
        $results =  $pdo->query($query);

        return $results;

    }catch(PDOException $ex){
        echo "EXCEPTION ".$ex;
    }
}

2 个答案:

答案 0 :(得分:1)

感谢@Cymbals的回答,最终的代码最终结果如下:

public function selectFrom($table,$indexes){
    try{
        $pdo=$this->getPdo();

        $columns = $this->getColumnNames($table);
        $finals = array();

        for($i=0;$i<count($indexes);$i++){
            $finals[$i] = $columns[$indexes[$i]];
        }

        $query = $this->getSelectSQL($table, $finals);
        $query.= " WHERE Available = 1";

        $stmt = $pdo->prepare($query);

        $stmt->execute();


        $results = $stmt ->fetchAll();
        return $results;            

    }catch(PDOException $ex){
        echo "EXCEPTION ".$ex;
    }
}

答案 1 :(得分:0)

获取查询后,请尝试此操作,准备并执行

      $stmt = $pdo->prepare($query);
      var_dump($stmt);// if the prepare fails or sql query is messed up it will give false
      $results = $stmt->execute();
      return $results;