在WHILE LOOP内按日期排序SQL

时间:2015-09-08 10:27:56

标签: php mysql date

我无法按日期对事件进行排序,因为我在一个表中有事件ID,而在另一个表中有事件日期。

代码如下。

$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";

我需要首先从另一个表中获取事件,称为注册 - 在此表中没有日期字段。

如何按日期对此列表进行排序?

3 个答案:

答案 0 :(得分: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";

答案 1 :(得分: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

答案 2 :(得分: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";