Llamasery.com Home  
 
Server-side Tutorial/Article: News & Events - Part 2 of 4
Alfie the alpha_geek: Llamasery guru-in-waiting Tutorials Purpose

Tutorials/Articles

Rate This
Visitor Comments
Feeling Secure
News & Events

Starter Tutorials

Starter Tutorials

News

No big secret here. Something happens that you think is newsworthy in the context of your site so you add another item to your News database. Assuming that your database table was set up to auto-increment the index, i.e. a new entry to the database table is always added to the end of the table, then all your news query needs to do is select a limited number of database records in descending order from the end of the database. For the five most recent news items:

SELECT * from $db_table ORDER BY id DESC LIMIT 5

How you present your news depends only on how you want to write the HTML code that displays the results of that type of query. Below is an example that assumes your news table contains two fields - id (primary, auto-increment) and news:

db field type/size extras
id tinyint (4) primary, auto-increment
news text  

<?php
include("news_config.php"); // provide $db_table and $news_lim values, etc.
include("db_conn.php"); // database host, name, user, password

// connect to host and select db
mysql_connect($host, $db_user, $db_pass) or die ("Can't connect!");
mysql_select_db($db_name) or die ("Can't open database!");

$query = "SELECT * from $db_table ORDER BY id DESC LIMIT $news_lim ";// select $news_lim results
$result = mysql_db_query($db_name, $query);

while ($myrow = mysql_fetch_array($result)) // loop through all results
   {
   echo "<p>". nl2br($myrow['news']). "</p>";// nl2br converts 'new lines' to <br>
   }
// loop done
?>

If you want to extend that example, you could add another field to the database such as a 'header' for the news item. You could also improve the look of the news display by adding special style definitions within the news_config.php file and have the database rows displayed like so, below:

while ($myrow = mysql_fetch_array($result)) // loop through all results
   {
   echo "<p style='". $hdr_style. "'>". $myrow['hdr']. "</p>";
   echo "<p style='". $news_style. "'>". nl2br($myrow['news']). "</p>";
   }

More News!

And if you want 'the news' on more than one page of your site, simply take the code you use to display it once, save it as show_news.php for example, and on every page where you want your news to display, add the following:

<?php
include("show_news.php");
?>

Enough News!

That's enough about 'news'. If you need 'all' the source code for this example, view & copy/paste this. What's coming soon?

«  previous  |  next  »