开发者

10 most recent rows from mySQL by time and define variables

I want to get the 10 most recent rows from a mysql database.

How can I do that?

+----+-------+----+-----------+
| id | value | ap | timestamp |
+----+-------+----+-----------+

And define variab开发者_JAVA百科les for value, ap, and timestamp... for each row!

like:

    $value1 = ?;
    $ap1 = ?;
    $timestamp1 = ?;

    $value2 = ?;
    $ap2 = ?;
    $timestamp2 = ?;
etc....


The simplest way is probably something like this:

$db = new PDO('mysql:host=<hostname>;port=<port>;dbname=<database name>', '<username>', '<password>');

$query = 'SELECT id, value, ap, `timestamp` '.
            'FROM <table> '.
            'ORDER BY `timestamp` DESC '.
            'LIMIT 10';

$resultset = $db->query($query);

$results = $resultset->fetchAll();

Then you will have a two-dimensional array with 10 sets of the values you want. $results[0]['id'], $results[0]['value'], $results[0]['ap'], and $results[0]['timestamp'], up through $results[9]['id'], etc.


You can get the data like so..

$query = mysql_query("SELECT * FROM `my_table` ORDER BY `timestamp` DESC LIMIT 10"); 

and you can use the results like so..

while($results = mysql_fetch_object($query)) {
    echo $results->value; 
    echo $results->ap;
    echo $results->timestamp; 
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜