Anocodious
Anocodious

Reputation: 21

Building an AJAX based news system

I've been working on building a news system for a little while now. I'm getting the markup for each news post as seen below:

        $newsArray = array();
        $result = News::getNews($database, 5);

        while($row = mysql_fetch_assoc($result))
              $newsArray[] = new News($row);

        foreach($newsArray as $news)
            echo $news->getMarkup($database);

Is this an effecient way of recieving my news posts? I have a file that contains my actual news post markup called newspost.html - and my getMarkup() function looks like this:

    public function getMarkup($database) {

        $html = file_get_contents('include/html/newspost.html');

        $find = array("{ID}", "{TITLE}", "{CONTENT}", "{USERNAME}", "{TIME}");
        $replace = array($this->data['news_id'], $this->data['title'], $this->data['content'], $this->data['username'], $this->data['time']);

         for ($i = 0; $i < count($find); ++$i) {
            $html = str_replace($find[$i], $replace[$i], $html);
         }

        return $html;
    }

obviously, I can't fetch a .php file, so I had to make my own solution of adding specific news information to each post. However, Im feeling this is very ineffecient.

I would love to get some advice on how to solve this in a more elegant manner. I don't want to embed my postnews code directly into my PHP function as I don't like mixing structure and content.

Feedback appreciated!

Upvotes: 2

Views: 415

Answers (2)

Nicholas Wilson
Nicholas Wilson

Reputation: 9685

It looks basically OK. The problems the other commentators have pointed out are not a big deal really. You database queries are slower than grabbing a file again from memory, and a bit of str_replace is neither here nor there.

The thing to tell us is what AJAX has got to do with this, and it's unclear what you are talking about in a couple of places (like 'can't fetch a PHP file').

Upvotes: 0

OneOfOne
OneOfOne

Reputation: 99205

1 fast fix, move $html = file_get_contents('include/html/newspost.html'); outside the getMarkup function.

and 1 other idea, do the html processing in the client side, just send the raw post data (json_encode) to your ajax code, have the ajax code do the processing.

Upvotes: 1

Related Questions