tags:

views:

120

answers:

3

topic.php

$id = isset($_GET['id']) ? intval($_GET['id']) : 0;

$query = mysql_query("SELECT * FROM topics WHERE id = $id");
$row = mysql_fetch_assoc($query);


$title = htmlspecialchars($row['title']);
$text = bbcode($row['text']);

view/topic.php

<h1><?=$title?></h1>
<p><?=$text?></p>

<h1>Replies</h1>

$q = mysql_query("SELECT * FROM replies WHERE topic_id = $id");
while ($r = mysql_fetch_array($q)) {
$text = bbcode($r['text']);
$date = $r['date'];
$poster = $r['poster'];
$edited = $r['edited'];

echo "<p>$text</p>";.......
}

As you can see I have some ugly code in the view/topic.php. Can I keep it in topic.php somehow? Not fun for a web designer to have to deal with all this.

Thanks!

+1  A: 

you could just throw all of that code into a function that returns whatever you need. then call the function echo func()

contagious
+3  A: 

You could try putting the code in viewtopic.php into a function into a function in topic.php.

It looks like you are already including topic.php in viewtopic.php, but if you're not, you'll want to do that, too.

For example, you would add this to topic.php:

function ViewTopic($id) {

     $q = mysql_query("SELECT * FROM replies WHERE topic_id = $id");
     while ($r = mysql_fetch_array($q)) {
     $text = bbcode($r['text']);
     $date = $r['date'];
     $poster = $r['poster'];
     $edited = $r['edited'];

     echo "<p>$text</p>";.......

}

And here's what viewtopic.php would look like:

<h1><?=$title?></h1>
<p><?=$text?></p>

<h1>Replies</h1>

ViewTopic($id);

}
gclaghorn
wow didnt think of that. very nice thanks
Note that both the original code and this answer contain a SQL Injection vulnerability. Anyone can pass whatever they want as the ID (including malicious SQL) and your code will execute it. See http://stackoverflow.com/questions/1973/what-is-the-best-way-to-avoid-sql-injection-attacks
Joe Kuemerle
Good catch. You should be careful about using $_GET in an SQL query.
gclaghorn
A: 

Using output buffering you can really easily create your own little template engine achieve even better logic / layout separation.

function renderView($viewFile, $data) {
 ob_start();
 extract($data);
 require($viewFile);
 return ob_get_clean();
}

The code above is from a little hobby project and it's not complete, but it's a good proof of concept. What it does is to extract key / value pairs from the $data hashmap making them available in the current scope. $data = array("name" => "Kim"); will make $name accessible inside the view.

All this is done within output buffering so you can do whatever you want with the output. You might want to implement caching, use it to render email (no more excessive string concatenation) and things like that.

Kimble