13.09.2016 Views

PHP and MySQL Web Development 4th Ed-tqw-_darksiderg

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

758 Chapter 31 Building <strong>Web</strong> Forums<br />

The most important thing that happens in this constructor is that the child nodes of<br />

this node are instantiated.You begin this process by checking whether you need to<br />

exp<strong>and</strong> the child nodes.You perform this process only if a node has some children, <strong>and</strong><br />

you have elected to display them:<br />

if(($sublist||$exp<strong>and</strong>) && $children){<br />

$conn = db_connect();<br />

You then connect to the database <strong>and</strong> retrieve all the child posts, as follows:<br />

$query = "select * from header where parent = '".$postid."' order by posted";<br />

$result = $conn->query($query);<br />

Next, you fill the array $m_childlist with instances of the treenode class, containing<br />

the replies to the post stored in this treenode, as follows:<br />

for ($count=0; $row = @$result->fetch_assoc(); $count++) {<br />

if($sublist || $exp<strong>and</strong>ed[$row['postid']] == true) {<br />

$exp<strong>and</strong> = true;<br />

} else {<br />

$exp<strong>and</strong> = false;<br />

}<br />

$this->m_childlist[$count]= new treenode($row['postid'],$row['title'],<br />

$row['poster'],$row['posted'], $row['children'], $exp<strong>and</strong>,<br />

$depth+1, $exp<strong>and</strong>ed, $sublist);<br />

}<br />

This last line creates the new treenodes, following exactly the same process we just<br />

walked through, but for the next level down the tree.This is the recursive part: A parent<br />

tree node calls the treenode constructor, passes its own postid as parent, <strong>and</strong> adds one<br />

to its own depth before passing it.<br />

Each treenode, in turn, is created <strong>and</strong> then creates its own children until you run out<br />

of replies or levels that you want to exp<strong>and</strong> to.<br />

After all that’s done, you call the root treenode’s display function (back in<br />

display_tree()), as follows:<br />

$tree->display($row, $sublist);<br />

The display() function begins by checking whether this is the dummy root node:<br />

if($this->m_depth > -1)<br />

In this way, the dummy can be left out of the display.You don’t want to completely skip<br />

the root node, though.You do not want it to appear, but it needs to notify its children<br />

that they need to display themselves.<br />

The display() function then starts drawing the table containing the articles. It uses<br />

the modulus operator (%) to decide what color background this row should have (hence<br />

they alternate):

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!