[SOLVED] Blog System

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
partiallynothing
Forum Commoner
Posts: 61
Joined: Fri Nov 21, 2003 5:02 pm
Location: connecticut, usa

[SOLVED] Blog System

Post by partiallynothing »

I have a news blog system on my site. With my surrent code it only displays the first one in the database (so the oldest one). I want it to display the latest five. What peramiters do I have to add to acomplish this.

Here's my code:

Code: Select all

<?php
if ($auth == 1) {
	$query = "SELECT * FROM news ORDER BY id DESC LIMIT 0 , 4";
	$result = mysql_query($query) or die(mysql_error());
	$row = mysql_fetch_row($result) or die(mysql_error()); 
	print "<BR><b>Author: </b> {$row['2']} <BR> <b>Subject: </b> {$row['3']} <BR> {$row['4']} <BR><BR>"; 
	} ?>
Thanks for any help!
User avatar
twigletmac
Her Royal Site Adminness
Posts: 5371
Joined: Tue Apr 23, 2002 2:21 am
Location: Essex, UK

Post by twigletmac »

You have to do a loop to get all the information out of the $result resouce:

Code: Select all

<?php
if ($auth == 1) {
   $query = "SELECT * FROM news ORDER BY id DESC LIMIT 0 , 4";
   $result = mysql_query($query) or die(mysql_error());
   while ($row = mysql_fetch_row($result)) {
       print "<BR><b>Author: </b> {$row['2']} <BR> <b>Subject: </b> {$row['3']} <BR> {$row['4']} <BR><BR>";
    }
}
 ?>
BTW, you could make it easier to maintain by accessing the variables using their field names from the table, so assuming that your fields are called author, subject and text, you could do:

Code: Select all

<?php
if ($auth == 1) {
   $query = "SELECT author, subject, text FROM news ORDER BY id DESC LIMIT 0 , 4";
   $result = mysql_query($query) or die(mysql_error());
   while ($row = mysql_fetch_assoc($result)) {
       print "<BR><b>Author: </b> {$row['author']} <BR> <b>Subject: </b> {$row['subject']} <BR> {$row['text']} <BR><BR>";
    }
}
 ?>
and achieve the same result but with more readable and maintainable code (ie. if a new field is added to the table it won't muck everything up).

Mac
User avatar
partiallynothing
Forum Commoner
Posts: 61
Joined: Fri Nov 21, 2003 5:02 pm
Location: connecticut, usa

Post by partiallynothing »

thanks a lot! That solved everything!
Post Reply