0

I'm confused how to display data from class.

I have database with entries and I created a sql request inside of a class:

class Posts 
{

public function getPosts (  ) {

    $returnValue = FALSE;


    $query = "SELECT * FROM posts ORDER BY post_modified";

    try {
        $pdoCore = Core::getInstance();
        $pdoObject = $pdoCore->dbh->prepare($query);

        if ( $pdoObject->execute() ) {

            $pdoObject->setFetchMode(PDO::FETCH_ASSOC);


            while ( $posts_row = $pdoObject->fetch() ) {

                $this->posts[] = $posts_row;
            }

            $returnValue = TRUE;
        }           
    }
    catch ( PDOException $pe ) {
        trigger_error( ' Veritabanindan bilgiler alinamadi. ' . $pe->getMessage() );
    }

    return $returnValue;

} 
}

and I'm trying to display it with this code

$posts = new Posts();

$posts->getPosts();


foreach ($posts as $key => $value) {
    echo $value;
}

as you notice I get Notice: Array to string conversion error and if I declare $this->posts as an array the page is blank.

Can you explain me how should retrieve data in this situation. is this approach right?

thanks.

Erdem Ece
  • 1,755
  • 5
  • 22
  • 42
  • `foreach ($posts->posts as $key => $value)` ? – Jonnix Apr 29 '15 at 18:38
  • yes all the data from database `array(12) { ["ID"]=> string(1) "1" ["post_author"]=> string(1) "1" ["post_date"]=> string(19) "2015-01-04 00:00:00" ["post_content"]=> string(18) "Ilk Yazininin yazi" ["post_title"]=> string(8) "ilk yazi" ["post_status"]=> string(6) "active" ["comment_status"]=> string(6) "active" ["post_modified"]=> string(19) "0000-00-00 00:00:00" ["post_type"]=> string(4) "text" ["comment_count"]=> string(1) "0" ["TotalVotes"]=> string(1) "0" ["VoteSum"]=> string(1) "0" }` – Erdem Ece Apr 29 '15 at 18:38

3 Answers3

1

In your foreach, $posts is the instance object of the Posts class, so it doesn't make sense to try to iterate the Posts object. Instead, I would build an array in the getPosts method and return it, rather than creating the posts property and returning a boolean.

Below, $returnValue is the local array that gets returned.

public function getPosts (  ) {

    $returnValue = array();

    $query = "SELECT * FROM posts ORDER BY post_modified";

    try {
        $pdoCore = Core::getInstance();
        $pdoObject = $pdoCore->dbh->prepare($query);

        if ( $pdoObject->execute() ) {

            $pdoObject->setFetchMode(PDO::FETCH_ASSOC);


            while ( $posts_row = $pdoObject->fetch() ) {

                $returnValue[] = $posts_row;
            }

        }           
    }
    catch ( PDOException $pe ) {
        trigger_error( ' Veritabanindan bilgiler alinamadi. ' . $pe->getMessage() );
    }

    return $returnValue;

} 

Then the usage:

foreach ($posts->getPosts() as $key => $value) {
    echo $value['post_title'];
}
MrCode
  • 63,975
  • 10
  • 90
  • 112
  • hi thanks. instead of `$returnValue[] = $posts_row;` and `return $returnValue;` i used `$this->posts[] = $posts;` and `return $this->posts;` and it works now. Can you explain me what is the difference between $this-> and $retrunValue which one should I use. For example would I need $this-> in future. I'm just trying to learn OOP in php – Erdem Ece Apr 29 '15 at 18:54
0

Your problem

I'm assuming that you have a posts field in your class that you didn't post here (because you do access it as $this->posts).

What happens in your foreach loop is that it iterates over all the fields of the Posts class, and echoes them (which doesn't make all that much sense, but ok). The problem is that posts is not a string, but an array, and you can't echo arrays. If you use print_r it should display you something.

Fixing the problem

What you actually want to do is return the posts in getPosts, and then iterate over that. So basically, return $this->posts (or an empty array for no posts, an exception for error), and then do something like this:

$posts = new Posts();

$posts2 = $posts->getPosts();

foreach ($posts2 as $key => $value) { // iterate over posts
    foreach ($value as $key2 => $value2) { // iterate over values of that post
    echo $value2;
}

A possibly better solution

Note that the variable names here are pretty bad. This is mainly because your posts object is unconventional. I would expect a Post object which contains fields such as name, last_modified, etc. A Posts class with a field containing a list of posts doesn't really make all that much sense (it's just a list of Posts, no need for a class).

If you want to add methods to retrieve all posts, you don't really need to store the resulting list in a class, just return the list of Post object, then you can iterate over that.

So I would change your code to:

class Post {
    $name;
    $last_modified;

    // constructor

    // getters
}

class PostDAO {

    public function getAll() {
        // retrieve posts from db, return array of Post objects
    }
}

And then use it like this:

$postDAO = new PostDAO();
$posts = $postDAO->getAll();

foreach ($posts as $post) { // iterate over posts    
    echo $post->getName();
    echo $post->getLastModified();
}

The advantage is that this decouples how posts are retrieved from the database from the rest of your code (eg displaying your posts).

tim
  • 1,999
  • 17
  • 32
  • how can I achieve this? $post->getName(); can you give me an example for getAll() method please? – Erdem Ece Apr 29 '15 at 19:32
  • 1
    @ErdemEce see here for how [getters work in PHP](https://stackoverflow.com/questions/4478661/getter-and-setter) (it's pretty much the same as in most language, eg Java, etc; I would not use magic methods, because they can't be documented and there is no auto-complete). `getAll` would just be what you already have, but without returning true/false (which isn't all that useful; if there is an error, just throw an exception), and returning an array of objects instead (created via something like `$returnValue[] = new Post($posts_row['column_name1'], $posts_row['column_name2'], [and so on];`). – tim Apr 29 '15 at 19:41
0

Your method getPosts() assign values to property $posts of object $posts. Try it:

$posts = new Posts();

$posts->getPosts();

foreach ($posts->posts as $key => $value) {
    echo $value;
}
Nick
  • 9,735
  • 7
  • 59
  • 89
  • I get these errors Notice: Undefined property: Posts::$posts in /var/www/tutorial.dev/index.php on line 16 Warning: Invalid argument supplied for foreach() in /var/www/tutorial.dev/index.php on line 16 – Erdem Ece Apr 29 '15 at 18:40
  • Because you must declare this property in your class – Nick Apr 29 '15 at 20:18