Johan Broddfelt

List the items

Now that we got some posts, we would like to display them in a list. So we need a function in our class that fetches an array of items. And of course we want the same function to work for all out classes so we put it in the Db.php. We also need a count function, to return how many items we actually have.

    // Fetch an array of items in a table as objects
    // Sample: $filter  = ' WHERE id > 50 ';
    // If you provide a subset of columns as values the query might be faster, But remember that you do not get all values in your objects
    function fetchArray($filter=' ORDER BY id ', $values=' * ') {
        $ret = array();
        $vals = '';

        if ($values != ' * ') {
            $fields = array();
            $fields = explode(',', $values);
        } else {
            $fields = $this->fetchFields();
        }
        $first = true;
        foreach ($fields as $field) {
            if (!$first) {
                $vals .= ', ';
            }
            $first = false;
            $vals .= $field->columnName;
        }
        $sql = "SELECT " . $vals . " FROM `" . $this->table . '` ' . $filter;
        #print $sql.'
'; $res = Db::query($sql); while($row = Db::fetch_assoc($res)) { $className = $this->className; $obj = new $this->className; $obj->fetchObject($row, $values); $ret[] = $obj; } return $ret; } function fetchCount($filter='') { $sql = "SELECT count(id) as cnt FROM `" . $this->table . '` ' . $filter; $res = Db::query($sql); while($row = Db::fetch_assoc($res)) { return $row['cnt']; } return 0; }

With our new function we can now create a new view in views/posts and call it items.php

fetchArray(); ?> fetchCount(); ?>

Posts

posts found
TitlePostedTags
title; ?> posted; ?> tags; ?>

And since the list looks a bit cramped, we add some styling to the table.list structure as follows, in the main.css

table.list th, table.list td {
  padding: 10px;
}
table.list th {
  background: #a73;
  color: #fff;
  font-weight: normal;
  text-align: left;
  border: 1px solid #962;
}
table.list td {
  border: 1px solid #a73;
}
table.list tr:nth-child(odd) td {
  background: #ffe;
}

Now it looks more like a real list. And we can add the link it (index.php?module=post&view=items) to our menu in the main_template.php

        

But since we also want to be able to click the posts to read the content we need to add a link in the list as this index.php?module=post&view=item&id=[post_number]. So now the list file looks like this:

fetchArray(); ?> fetchCount(); ?>

Post list

posts found
TitlePostedTags
title; ?> posted; ?> tags; ?>

- framework, php, database, software

<< Fetch a specific post
Follow using RSS
One list to rule them all >>

Comment

Name
Mail (Not public)
Send mail updates on new comments
0 comment