-4

I want to get the latest entry from my database in php, I've tried the but still it is returning the first entry of the database

  1. I've tried this line
  2. Could it be from my database arrangement

    <?php
    $sql = "SELECT * FROM comments ORDER BY 'id' DESC LIMIT 3";
    $result = mysql_query($sql);
    ?>
    
Jason
  • 15,017
  • 23
  • 85
  • 116
  • 8
    See [when to use single quotes, double quotes, backticks](http://stackoverflow.com/questions/11321491/when-to-use-single-quotes-double-quotes-and-backticks).. Your column name `id` should _not_ be single-quoted in the `ORDER BY` clause. Quoting it causes it to be interpreted as a string literal, the same literal for all rows, and therefore a meaningless `ORDER BY`. – Michael Berkowski Jan 27 '14 at 03:32

2 Answers2

0

Try this

$sql = "SELECT * FROM `comments` ORDER BY `id` DESC LIMIT 1";
  • make sure you use backticks to identify column names, using quotes tells MySQL to treat the string as text
  • you had LIMIT 3 which would try to return 3 lines...changing that to 1 will give you a single entry provided you do not reuse id values in any way.
  • you also should swap out mysql_* for mysqli_* functions as the mysql_* versions are deprecated
  • not sure what you are doing but keep away from SELECT *. It's better to name only the columns you need to return
Jason
  • 15,017
  • 23
  • 85
  • 116
0

Try this code. Please make sure that id is an auto-increment column.

$sql = "SELECT * FROM comments ORDER BY id DESC LIMIT 1";
$result = mysql_query($sql);
Dulitha K
  • 2,088
  • 1
  • 19
  • 18