Jim wrote:
I'm using PHP & MySQL to create a simple guestbook. I've created my
table and I'm able to load my information in as usual. I would like it
to display the latest entry first though. I set an id to each entry
that is auto-incremented. The idea seems real easy in theory:
1. Create a loop that starts at the last entry and goes until it
finishes the first.
2. Each time around display the entire entry.
My question is, how do I find the last entry if I don't know what it is?
For example, right now I have three entries and I can display them
starting with the first. I know there are three so I set my counter to
start at 0 and end on 2 (0,1,2) now if I want to reverse it and start
with the last, how do I get the last id?
Any help would be appreciated.
heh counter thats funny... dont use counter.. please :)
mysql_query returns resourse thats array of records
uses the mysql_fetch_row or mysql_fetch_array as listed below
the rows will already be sorted into correct order by the DB query
actual working code follows
1: dbconnect() is a simple function that logs into the db with set
username and password returning the resource handle
2: indx is an autoincrementing value in the table.
sorting by index will sort by entry order :D
--START CODE--
if ( ($dbl = dbconnect()) == DBCONNERROR){
echo "<h2>Guest book is currently unavailable for viewing. Please
try again later.</h2>\n";
} else {
$author = ""; $dtime=""; $message="";
$query = "SELECT * FROM GuestBook ORDER BY indx DESC";
$result = mysql_query($query);
if (!($result)){
echo "Error reading Guestbook<br>";
print_r($result);
} else {
$posts = mysql_num_rows($result);
while ($record = mysql_fetch_row($result)) {
$enid = $record[0];
$author = $record[2];
$dtime = $record[3];
$message = $record[4];
$pub = $record[1];
$by = "<b>By</b> : <i>$author</i><br>\n";
$dt = "<b>Date</b> : <i>$dtime</i><br>\n";
$ms = "<q>$message</q>\n";
$entry = "<hr><p>";
$entry .= "$by";
$entry .= "$dt";
$entry .= "$ms</p>";
echo $entry;
}
}
mysql_close($dbl);
}
--END CODE--
as i said this code works on actual site.
mysql creation statement for table GuestBook is :
CREATE TABLE `GuestBook` (
`indx` int(11) NOT NULL auto_increment,
`public` enum('yes','no') NOT NULL default 'yes',
`author` varchar(50) NOT NULL default '',
`tstamp` varchar(100) NOT NULL default '',
`message` blob NOT NULL,
PRIMARY KEY (`indx`)
) TYPE=MyISAM;
with this table and the preceding code you should be up in no time :D
hth
JV