Page 1 of 1

[SOLVED] Blog System

Posted: Thu Nov 27, 2003 9:17 am
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!

Posted: Thu Nov 27, 2003 9:27 am
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

Posted: Thu Nov 27, 2003 10:00 am
by partiallynothing
thanks a lot! That solved everything!