Selecting Max timestamp

Hi everyone,

I have a table where I need to select the row containing the maximum timestamp.

time is of type timestamp


$sql2="	SELECT * FROM userdata WHERE time=MAX(time)";
		
$result=mysql_query($sql2) or die(mysql_error());
	
$output=mysql_fetch_array($result);
	
echo "<br /><br />";
echo $output['time'];
echo "<br /><br />";

I’m getting the output “Invalid use of group function”

If I try


$sql2="SELECT MAX(time) FROM userdata";

$result=mysql_query($sql2) or die(mysql_error());
	
$output=mysql_fetch_array($result);
	
echo "<br /><br />";
echo $output['time'];
echo "<br /><br />";

I get “Undefined index: time”

Does anyone know what I’m doing wrong?

Thank you very much.

Thanks everyone, I think I got it.


$sql2="	SELECT * FROM userdata WHERE time=(select MAX(time) from userdata)";

I wonder if this is really the best way of finding the maximum though?

yes. two things:

  1. don’t call your column time. that is a reserved word in mysql. use something else like ts (for timestamp) (but don’t use timestamp, because that’s a reserved word, too)
  2. don’t use *. explicitly name the columns you are using, even if you are using them all.

Hi Longneck:

Why not use *?

Thx,

  • AAA

Why “select star” is bad

Thanks for the replies everyone, I really appreciate it.