3

I have been trying for over a day now to get FetchAll() method to help me display array from database. But all my efforts have failed. Instead of the print_r() returning an array, it gives me this array(). Kindly, help me out. The code in class page :

class Article {
public function fetch_all(){
    global $conn;
    $ass = $conn->prepare("SELECT * FROM articles");
    $ass->execute();
     return $ass->fetchAll();


    }

} 

while the code in display page is:

$article = new Article;
$articles = $article->fetch_all();
 print_r($articles);
user2947216
  • 39
  • 1
  • 4

4 Answers4

4

$query is not defined in your code, $ass->fetchAll(); is what you should have.

Musa
  • 96,336
  • 17
  • 118
  • 137
  • the problem persists when I use $ass->fetchAll(); This has been frustrating. Can you think up another reason why the array will be empty? – user2947216 Mar 24 '14 at 05:55
0

$query is not defined. Consider injecting your database object into the Article object to avoid using globals.

class Article {
   public function fetch_all(PDO $conn){
    $ass = $conn->prepare("SELECT * FROM articles");
    $ass->execute();
        return $ass->fetchAll();  
    }

} 

$article = new Article;
$articles = $article->fetch_all($conn);
print_r($articles);

Injecting your PDO object can make changing the code easier down the line.

Ryan
  • 14,392
  • 8
  • 62
  • 102
  • I have changed $query to $ass, but the array() is still empty. I keep the database object separate because I want the coding to be tidy. Can the use of global cause the problem of empty array()? – user2947216 Mar 24 '14 at 05:59
0

I have tried the following code below it works perfect.

class Article {
        public function fetch_all(){
            global $connection;
            $ass = $connection->prepare("SELECT * FROM test");
            $ass->execute();
            return $ass->fetchAll();
        }
    } 


    $article = new Article;
    $articles = $article->fetch_all();
    print_r($articles);

As you see above i have used my $connection and it works perfect. So, the problem is definitely on your $conn (connection). check your connection again.

MR.Internet
  • 547
  • 4
  • 19
0

It has eventually started returning full array. All I did was to uninstal the WAMPserver I was using and replace it with another one.

user2947216
  • 39
  • 1
  • 4