2015-08-25 41 views
-1

如何從MySQL $row[id]$row[timestamp]中獲取id和時間戳記結果,並對結果進行排序並獲取具有最新匹配時間戳的id數組? 所以,如果我的MySQL數據庫中有這個數據,如何對MySQL結果進行排序,然後獲取PHP中最新的10個日期時間的標識

3,2015-08-24 10:38:3134,2015-08-24 10:38:168,2015-08-24 10:38:51

我會爲了從最新到最舊的時間戳,最終落得一個數組,該ID的的。

8,3,34

這裏是我的代碼省略信息。

$servername = "IP:PORT"; 
$username = "USERNAME"; 
$password = "PASSWORD"; 
$dbname = "DB"; 
$conn = new mysqli($servername, $username, $password, $dbname); 
if ($conn->connect_error) { 
    die("Connection to the database failed. Please try again. Error: " . $conn >connect_error); 
} 
$sql = "SELECT id, timestamp FROM posts ORDER BY timestamp DESC LIMIT 1,10;"; 
$result = $conn->query($sql); 
$arrays = array(); 
if ($result->num_rows > 0) { 
    while($row = $result->fetch_assoc()) { 
     $arrays[] = $row[id]; 
    } 
} 
foreach ($arrays as $key => $id) { 
    $servername = "IP:PORT"; 
    $username = "USERNAME"; 
    $password = "PASSWORD"; 
    $dbname = "DB"; 
    $conn = new mysqli($servername, $username, $password, $dbname); 
    if ($conn->connect_error) { 
     die("Connection to the database failed. Please try again. Error: " . $conn->connect_error); 
    } 
    $sql = "SELECT name,timestamp,text FROM posts WHERE id=\"" . $id . "\";"; 
    $result = $conn->query($sql); 
    $arrays = array(); 
    if ($result->num_rows > 0) { 
     while($row = $result->fetch_assoc()) { 
      $date = date_create_from_format('Y-m-d H:i:s',$row[timestamp]); 
      $timezone = new DateTimeZone('America/Los_Angeles'); 
      $timedate = date_timezone_set($date, $timezone); 
      $finaltimedate = $timedate->format('Y-m-d h:i:s A'); 
      echo "<hr><h4>" . $row[name] . "<span style=\"float:right\">Time Posted: " . $finaltimedate . "</span></h4><br>"; 
      echo $row[text] . "<br>"; 
     } 
    } 
} 

然而,當我重新加載該頁面,它只是顯示了相同的,ID = 0,博客文章而不是發佈0和4(僅2個)的2。

+0

34將是最古老的,不是最新的,等 – Drew

+1

這是一個'由dtColumn遞減限制10' – Drew

+0

你可以嘗試改善這一問題的格式選擇等等,從tablexxx秩序等等? – Strawberry

回答

3

如果我正確理解你的問題,那麼這個查詢應該適合你。

SELECT id, timestamp FROM TABLE_NAME ORDER BY timestamp DESC LIMIT 1,10; 
+0

對不清楚的問題,但感謝您的幫助。這對我有效。 – Josh

相關問題