1

I have a section of my website that reads out data to the user.

My current code reads out data in the same order, even when new records are added; they are added at the end of the data that is being echoed out. I want to read out the most recent data as I am creating a message board.

CODE:

session_start();
$sess = $_GET['id'];
$profile_query = "SELECT * from forum WHERE postee = $sess";
$profile_queried = mysql_query($profile_query);
while($row = mysql_fetch_array($profile_queried))
{
    echo '<div class="each_post"><p>'.$row['content'].'</p></div>';
}

Question: How can I echo data from a database in order of recency? Must I add another field to do this?

Mohit S
  • 13,723
  • 6
  • 34
  • 69
Robert Tossly
  • 613
  • 1
  • 6
  • 14
  • You should use date field to achieve this task – Harshit Sep 09 '15 at 03:24
  • This is very unsafe code. Someone could easily trash your server. You may want to browse over this: http://stackoverflow.com/questions/11839523/secure-against-sql-injection-pdo-mysqli – flcoder Sep 09 '15 at 03:43

1 Answers1

3

Your query should be:

$profile_query = "SELECT * from forum WHERE postee = $sess ORDER BY id DESC"
aldrin27
  • 3,407
  • 3
  • 29
  • 43
  • Hmm getting a boolean error when I add this. **mysql_fetch_array() expects parameter 1 to be resource, boolean given** – Robert Tossly Sep 09 '15 at 03:28
  • @RobertTossly there must be some `column` that should have `increment value`, be sure you're using that name in query instead of `id` – Mubin Sep 09 '15 at 03:30
  • @RobertTossly try like this `$profile_query = "SELECT * from forum WHERE postee = '$sess' ORDER BY postee DESC"` – Shehary Sep 09 '15 at 03:30
  • @RobertTossly Change your code to this: `mysql_fetch_array($profile_queried, MYSQL_ASSOC)` – aldrin27 Sep 09 '15 at 03:32
  • I prefer that it must be date to be desc. @RobertTossly Can i know the column name of your date? – aldrin27 Sep 09 '15 at 03:37
  • `if( ! $profile_queried )` then your query failed and you don't have a valid resource to pass to mysql_fetch_array(), you can discover exactly why with mysql_error http://php.net/manual/en/function.mysql-error.php, also, note that mysql is deprecated, mysqli or PDO is recommended. – flcoder Sep 09 '15 at 03:50
  • Ahhh I've added an id auto-incrementing column. Then I have added ORDER BY id DESC. Thanks for showing me my problem. – Robert Tossly Sep 09 '15 at 03:50