2015-09-08 27 views
1

我按日期排序我的事件時遇到問題,因爲我在一個表中有事件ID,另一個表中有事件日期。在WHILE LOOP中按日期排序的SQL順序

代碼如下。

$getEventIds = "SELECT * FROM rz6wq_ohanah_registrations WHERE email='".$userEmail."'"; 
$result = mysqli_query($conn, $getEventIds); 

echo '<br />'; 

if ($result->num_rows > 0) { 
    // output data of each row 
    while($row = $result->fetch_assoc()) { 
     $getEventTitle = "SELECT * FROM rz6wq_ohanah_events WHERE ohanah_event_id=" . $row['ohanah_event_id'] . " ORDER BY date ASC"; 
     $title = mysqli_query($conn, $getEventTitle); 
     $rowTitle = $title->fetch_assoc(); 
     $originalDate = $rowTitle["date"]; 
     $newDate = date("d-m-Y", strtotime($originalDate)); 
     date_default_timezone_set('Europe/Copenhagen'); 
     $currentDate = date('d/m/Y'); 
     if(strtotime($currentDate) < strtotime($newDate)){   
     //echo "id: " . $row["ohanah_event_id"] . "<br>"; 
     echo "<div class='eventsTilmeldt'>"; 
     echo "<b>" . utf8_encode($rowTitle["title"]) . "</b><br>"; 
     echo "<br>"; 
     echo "Status: "; if($row["paid"] == 0){echo "<span style='color:red;'>ej betalt</span>";}else{echo "<span style='color:green;'>betalt</span>";} 
     echo "<br>";   
     echo "Dato: " . $newDate . "<br>"; 
     echo "Tidspunkt: " . $rowTitle["start_time"] . "<br>";   
     echo "<br>";   
     echo "Adresse: " . utf8_encode($rowTitle["adress"]) . "<br>"; 
     echo "By: " . utf8_encode($rowTitle["geolocated_city"]) . "<br>"; 
     echo "Sted: " . utf8_encode($rowTitle["venue"]) . "<br>";     
     echo "</div>"; 
     echo "<br>"; 
     }else{ 
      echo ""; 
     } 

    } 
} else { 
    echo "Ingen tilmeldte events."; 
} 

問題是它沒有按日期正確排序我的事件。我認爲它與它在while循環內我按日期排序有關嗎?

"SELECT * FROM rz6wq_ohanah_events WHERE ohanah_event_id=" . $row['ohanah_event_id'] . " ORDER BY date ASC"; 

我需要從另一個表獲得該事件的第一個叫做登記 - 這個表裏面有沒有日期字段。

如何按日期對此列表進行排序?

+0

你是第二個查詢僅返回一行。該查詢按日期排序,但由於只有一行返回,因此不起作用。 – mfisher91

+0

是的,我同意這一點,也許你可以修改你的查詢並將其移到循環之外。 – Makudex

回答

2

您可以使用JOIN代替:

$getEventIds = "SELECT reg.*,event.* FROM rz6wq_ohanah_registrations as reg 
JOIN rz6wq_ohanah_events as event ON reg.ohanah_event_id=event.ohanah_event_id 
WHERE email='".$userEmail."' 
ORDER BY event.date ASC"; 
+2

只要打敗我幾秒鐘! – Saty

+0

完美的作品!謝謝:) –

+1

@saty耶!好極了!好極了! –

1

爲什麼要用兩個查詢你可以做到這一點單查詢

SELECT A.*,B.* FROM rz6wq_ohanah_registrations AS A JOIN 
rz6wq_ohanah_events AS B ON A.ohanah_event_id=B.ohanah_event_id WHERE 
    A.email='".$userEmail."' ORDER BY B.date ASC 
+0

只要打我幾秒...太:)! –

+0

@HalayemAnis我們都提供相同的邏輯! – Saty

1
$getEventIds = "SELECT * FROM rz6wq_ohanah_registrations AS ROR, z6wq_ohanah_events AS ZOE WHERE ROR.ohanah_event_id = ZOE.ohanah_event_id AND ZOE.email = '" . $userEmail . "' ORDER BY date ROR.ASC";