1

My code gives me the following error:

Invalid use of group function

$query = mysql_query("SELECT `text` FROM `text` WHERE `id`=max(id)");
   if(!$query)
die(mysql_error());
  while($row = mysql_fetch_array($result))
  {
   echo $row['text'];
}

Where is my mistake?

ekad
  • 14,436
  • 26
  • 44
  • 46
Michael Naidis
  • 116
  • 2
  • 4
  • 15
  • 3
    Please. Stop using `mysql_query` in new code, it's a deprecated interface. You're just writing something that'll fail completely when those methods will be removed in future versions of PHP. [Switching to PDO is not hard](http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/) and will provide a number of other benefits. – tadman Jun 12 '13 at 16:39

2 Answers2

5

If you want the row with highest id you could use: SELECT text FROM text ORDER BY id DESC LIMIT 1

Michael Krikorev
  • 2,126
  • 1
  • 18
  • 25
5

WHERE clauses affect individual rows, whereas HAVING clauses affect aggregations (results of GROUP BY clauses). Row criteria must be limited to the WHERE clause, aggregate functions (like MAX) must be used in HAVING clauses.

You could do this:

SELECT *

FROM   text

WHERE  id = (SELECT MAX(id) FROM text);
Tom
  • 6,593
  • 3
  • 21
  • 42