当IF满足要求时,停止执行LOOP

时间:2015-12-03 02:34:36

标签: javascript php for-loop popup do-while

我已尝试在stackoverflow中找到解决我问题的解决方案,但其中没有一个与我的问题相符。

我的问题是;

if statement里面javascript if statement内有if statement弹出窗口。我希望我的javascript仅在if statement符合条件时显示弹出窗口1次。我尝试在<?php if(isset($_POST['submit'])){ $reserve_stime = htmlentities($_POST['starttime']); $reserve_etime = htmlentities($_POST['endtime']); $reservedstime = "SELECT startmeetingtime, endmeetingtime FROM meeting_room_reservation WHERE room_reserve_session = '$varsession' AND room_reserve_date = '$convardate' AND room_id = $idroom"; $result7=mysql_query($reservedstime) or die("invalid query:".mysql_error()); while($row7=mysql_fetch_assoc(@$result7)){ $reservedstime2 = "SELECT timereserve_start_id FROM timereserve_start WHERE timereserve_start_id BETWEEN " . $row7['startmeetingtime'] . " AND " . $row7['endmeetingtime'] . ""; $result8=mysql_query($reservedstime2) or die("invalid query:".mysql_error()); while ($row8=mysql_fetch_assoc(@$result8)) { $timealreadyreserved = $row8['timereserve_start_id']; echo "<script type='text/javascript'> for (i=$reserve_stime; i <= $reserve_etime ; i++){ if (i == $timealreadyreserved){ alert('Time is not Available'); break; } else{ //do nothing } } </script>"; } } } ?> 内使用break,但它仍会显示一段时间的弹出窗口。

代码:

for

我的朋友说,问题出现在do循环之前while break循环,这就是为什么弹出窗口仍会显示几次甚至已经放置{{1} } if statement

任何想法? 谢谢, faizal

1 个答案:

答案 0 :(得分:1)

您可以使用布尔变量(如$flag)来检查条件是否已满足,然后突破循环,如下所示:

// your code

while($row7=mysql_fetch_assoc(@$result7)){
    $reservedstime2 = "SELECT timereserve_start_id
                        FROM timereserve_start 
                        WHERE timereserve_start_id BETWEEN " . $row7['startmeetingtime'] . " AND " . $row7['endmeetingtime'] . "";
    $result8=mysql_query($reservedstime2) or die("invalid query:".mysql_error()); 

    $flag = false;
    while($row8=mysql_fetch_assoc(@$result8)) {
        $timealreadyreserved = $row8['timereserve_start_id'];

        for ($i=$reserve_stime; $i <= $reserve_etime ; $i++){
            if($i == $timealreadyreserved){
                $flag = true;
                ?>
                <script>alert("Time is not Available");</script>
                <?php
                break;
            }
        }
        if($flag){
            break;
        }
    }
    if($flag){
        break;
    }

}

// your code 

警告:不要在代码中混用javascript和php,就像在内部for循环中一样。

旁注:不要使用mysql_数据库扩展,它们在PHP 5.5.0中已弃用,并已在PHP 7.0.0中删除。请改用mysqliPDO扩展程序。这是why you shouldn't use mysql_ functions