【问题标题】:While and for loop not workingWhile 和 for 循环不起作用
【发布时间】:2014-10-15 16:14:05
【问题描述】:

我有一个问题,我认为有一个非常简单的解决方案,但我现在忙了 12 个小时,我不知道这个问题的解决方案。

我有一个包含多个数据的数据库。重要的数据是我保存在数据库中的时间。我想构建一个模块,提供 08:00 到 17:00 的数据。例如:

08:00 可用 09:00 不可​​用 10:00 可用 11:00 可用 12:00 可用 13:00 可用 14:00 可用 15:00 可用 16:00 可用 17:00 不可​​用

我将使用以下代码

$mysql['avail'] = mysql_query("SELECT time FROM `module` WHERE `date` = '" . $dbdate . "' ORDER BY date");
while($avail = mysql_fetch_assoc($mysql['avail'])){

  $hour = date('s',$avail['time']);

  for ($i = 8;$i <= 17; $i++) {

    if($hour == $i) {

        echo $i.':00&nbsp;not available<br />';

    } else {


        echo $i.':00&nbsp;available<br />';

    }

  } 

}

现在我得到以下输出:

08:00 可用 09:00 不可​​用 10:00 可用 11:00 可用 12:00 可用 13:00 可用 14:00 可用 15:00 可用 16:00 可用 17:00 可用 08:00 可用 09:00 可用 10:00 可用 11:00 可用 12:00 可用 13:00 可用 14:00 可用 15:00 可用 16:00 可用 17:00 不可​​用

无论我尝试什么,我都没有办法让它正确。有没有人可以帮助我?

【问题讨论】:

  • 问题不清楚
  • 您的查询可能容易受到SQL Injection Attacks的攻击
  • Vadim 的答案是正确的解决方案。

标签: php mysql datetime time


【解决方案1】:

您必须首先获取所有可用时间,然后使用您的时间表循环并检查每个小时是否在可用时间数组中。

类似的东西

$not_available_hours = array();
$mysql['avail'] = mysql_query("SELECT time FROM `module` WHERE `date` = '" . $dbdate . "' ORDER BY date");
while($avail = mysql_fetch_assoc($mysql['avail'])){
    $not_available_hours[] = date('s',$avail['time']);
}

for ($i = 8;$i <= 17; $i++) {
    if (in_array($i, $not_available_hours) {
        echo $i.':00&nbsp;not available<br />';
    } else {
        echo $i.':00&nbsp;available<br />';
    }
}

【讨论】:

  • 我没有足够的积分,但这就是解决方案。非常感谢
【解决方案2】:

你可能应该使用 mysql HOUR 函数来获取小时。

$mysql['avail'] = mysql_query("SELECT HOUR(time) as `hour` FROM `module` WHERE `date` = '" . $dbdate . "' ORDER BY date");
while($avail = mysql_fetch_assoc($mysql['avail'])){

  $hour = $avail['hour'];

  for ($i = 8;$i <= 17; $i++) {

    if($hour == $i) {

        echo $i.':00&nbsp;not available<br />';

    } else {


        echo $i.':00&nbsp;available<br />';

    }

  } 

}

你不应该使用mysql函数,而是mysqli

【讨论】:

    【解决方案3】:

    我认为这会产生欲望的结果:

    $mysql['avail'] = mysql_query("SELECT time FROM `module` WHERE `date` = '" . $dbdate . "' ORDER BY date");
    $notAvailable = array();
    while($avail = mysql_fetch_assoc($mysql['avail'])){
     $notAvailable[] = date('s',$avail['time'])
    }
      for ($i = 8;$i <= 17; $i++) {
    
        if(in_array($i, $notAvailable) {
            echo $i.':00&nbsp;not available<br />';
        } else {
            echo $i.':00&nbsp;available<br />';
        }
    
      }
    

    【讨论】:

      猜你喜欢
      • 2020-03-30
      • 1970-01-01
      • 1970-01-01
      • 2018-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-18
      • 2012-06-13
      相关资源
      最近更新 更多