PDA

View Full Version : displaying most recent entry from db



dru_nasty
December 3rd, 2005, 04:21 PM
I'm trying to learn the building blocks of php w/mysql.

I have a table called 'testTable' with two columns, 'id' and 'testField'.
id is auto_incremented . I've got 4 rows basically like this:

id testField
1 some text
2 more text
3 some more text
4 and more text

I would just like to get the latest entry from the db which would be "and more text".

so here's my code so far:


<?php
$conn = mysql_connect("localhost", "myusername","mypassword");
mysql_select_db("mydatabase_name", $conn);

$sql = "SELECT testField FROM testTable WHERE id=max(id)";
$result = mysql_query($sql, $conn) or die(mysql_error());
echo "$result";
?>

And the result i get from that query is this "Invalid use of group function".

How would i get only the latest entry from the db to display?

dru_nasty
December 3rd, 2005, 04:27 PM
nevermind, got it


/* Order by (id) descending and subsequently retrieve only the first element */
$sql = "SELECT testField FROM testTable ORDER BY id DESC LIMIT 1";
$result = mysql_query($sql, $conn) or die(mysql_error());

/* Fetch data from result set into an associative array */
$row = mysql_fetch_assoc($result);

/* Access any SELECT'ed fields via $row['field_name'] */
echo $row['testField'];