2011-08-27 18 views
9

Sto costruendo un sistema di note sul mio sito e sono arrivato allo stadio in cui gli utenti possono inserire note nel database MySQL usando PHP e poi PHP li stampa su una pagina. Tuttavia, quando stampano/echo, il più vecchio appare per primo ma voglio il più recente per primo. Voglio anche che siano limitati a 10, quindi solo 10 appaiono sulla pagina. Ecco il mio codice PHP, il vostro aiuto sarà molto apprezzato:PHP e MySQL: ordine per data e limite più recenti 10

// initialize some variables 
$notedisplaylist = ""; 
$myObject = ""; 
$result = mysql_query("SELECT * FROM notes WHERE note_author_id='$u_id' ORDER BY   date_time"); 

while($row = mysql_fetch_array($result)){ 
    $note_title = $row["note_title"]; 
    $note_body = $row["note_body"]; 
    $date = $row["date_time"]; 
    $notedisplaylist .= '<h2>' . $note_title . '</h2><br /><p>' . $note_body . '</p><hr /><p>Noted: ' . $date . '</p><hr /><br />'; 
} 

risposta

22

Questo dovrebbe farlo:

$result = mysql_query("SELECT * FROM notes WHERE note_author_id='$u_id' ORDER BY date_time DESC LIMIT 0, 10"); 
7

Prova

$result = mysql_query("SELECT * FROM notes WHERE note_author_id='$u_id' ORDER BY date_time DESC LIMIT 10"); 

Per una spiegazione più dettagliata su ORDER e LIMIT, visitare articoli del doc MySQL su sorting rows e la base select syntax (cercare una pallottola che descriva LIMIT).

6

danno come

ORDER BY date_time DESC 

altrimenti li esegue l'ordinamento in ordine crescente .. ecco perché quelli più vecchi vengono prima

9

uso:

SELECT * FROM notes WHERE note_author_id='$u_id' ORDER BY date_time DESC LIMIT 10 

DESC: ordine decrescente (dal più recente al più vecchio) LIMITE 10: trovati i primi 10 record.

5

Fate questo

$result = mysql_query("SELECT * FROM notes WHERE note_author_id='$u_id' ORDER BY date_time DESC LIMIT 0, 10"); 
0

Se nel caso in cui si desidera che il limite per essere una variabile, qui ho chiamato $ limite:

"SELECT * FROM tbl ORDER BY input_date DESC LIMIT 0, $limit"; 
Problemi correlati