Creating A PHP Application

RETRIEVE BLOG ENTRIES

Now that blog entries can be created, they need to be retrieved in order to be displayed. This is achieved with the use of a single SELECT statement. The page to view the last 5 blog entries will be the main index.php page.

This file is far less complex than the previous examples as it requires only a single query to extract the data and then display it. The conn.php file is included and a check is made for a valid database connection. Further checks are then made to ensure a valid database resource is available and if all is well, the blog data is SELECTed from the database.

The data is put into an array of blog data for use further down the script in the display where a simple foreach loop echoes each record in a little box that can later be styled with CSS.

The index.php file will look like this.


<?php

/*** include the header ***/
include 'includes/header.php';

/*** include the database connection ***/
include 'includes/conn.php';

/*** check for valid database connection ***/
if($db)
{
/*** the SQL query to select last 5 blogs ***/
$sql = "SELECT
blog_content_headline,
blog_content_text,
DATE_FORMAT(blog_content_date, '%b %d %Y') AS blog_content_date,
blog_category_name,
blog_user_name
FROM
blog_content
JOIN
blog_users
USING(blog_user_id)
JOIN
blog_categories
USING(blog_category_id)
ORDER BY blog_content_id DESC
LIMIT 5";

/*** run the query ***/
$result = mysql_query($sql) or die(mysql_error());

/*** create the blog array ***/
$blog_array = array();

/*** check for a valid resource ***/
if(is_resource($result))
{
/*** check there are results ***/
if(mysql_num_rows($result) != 0)
{
/*** stuff the blog entries into the blog array ***/
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$blog_array[] = $row;
}
}
}
else
{
echo 'Blog Unavailable';
}
}
else
{
echo 'No Blog Entries Available';
}
?>

<h1>PHPRO.ORG Blog</h1>
<p>
Welcome to the PHPRO.ORG Blog...
</p>

<?php

if(sizeof($blog_array) > 0)
{
/*** loop over the blog array and display blogs ***/
foreach($blog_array as $blog)
{
echo '<div class="blog_entry">';
echo '<p><span class="category">'.$blog['blog_category_name'].': </span>
<span class="blog_date">Added by '.$blog['blog_user_name'].' on '.$blog['blog_content_date'].'</p>';
echo '<h2>'.$blog['blog_content_headline'].'</h2>';
echo '<p>'.$blog['blog_content_text'].'</p>';
echo '</div>';
}
}
else
{
echo 'No Blogs Here';
}

/*** include the footer file ***/
include 'includes/footer.php';
?>

Advertisements