<?
	require_once("includes/config.php");

	// construct a base query that will retrieve all posts and JOIN them with the users table to get the author's name
	$query = "SELECT posts.*, CONCAT(users.first_name, ' ', users.last_name) as author FROM posts JOIN users ON posts.user_id = users.id";
	
	if(isset($_GET["search"]) && !empty($_GET["search"]))
	{
		// escape the search string to protect the db
		$search = mysql_real_escape_string($_GET["search"]);
		
		// append WHERE clause to look for the search term in the title or content fields
		$query = $query . " WHERE title like '%$search%' or content like '%$search%'";
	}
	
	// append sort order
	$query = $query . " ORDER BY posts.date desc";
	
	// execute query
	$result = mysql_query($query);
	if($result === FALSE)
	{
		exit( "Could not query database: " . mysql_error() );
	}
?>

<? require_once("templates/begin.php"); ?>

<? if(isset($search)) { ?>
	<div id="contentnav">
		<h6><a href="index.php">&#60; home</a> | Search for "<? echo htmlspecialchars($search); ?>" found <? echo mysql_num_rows($result); ?> result<? echo((mysql_num_rows($result)==1) ? "" : "s"); ?></h6>
	</div>
<? } ?>

<? 
	while($post = mysql_fetch_object($result))
	{
		blog_displaypost($post);
	}
?>

<? require_once("templates/end.php"); ?>
