使用foreach php循环中的三元运算符在下拉列表中选择值

时间:2018-02-25 16:18:46

标签: php mysql

如何在foreach循环中选择下拉值。下面的代码产生30分钟差距的时间。我无法从mysql数据库中选择值。

$sql = "SELECT * FROM batches WHERE batch_id = '$id'";
$result = mysqli_query($con, $sql);

while ($row = mysqli_fetch_array($result)) {

    // Name
    echo "<label>Batch name</label> ";
    echo "<input type=text name=name value='".$row['name']."' required> <br />";

    // Start time
    echo "<label>Start time</label> ";
    echo "<select name=starttime value=''> Start time </option>";
        $range = range( strtotime("05:00"), strtotime("21:00"), 30 * 60);
        foreach($range as $time){
            $foo = date("H:i", $time) . "</br>";
            $selected = ($foo == $row['start_time']) ? 'selected="selected"' : '';
            echo "<option value='$foo'" . $selected . ">" . $foo . "</option>";
        } // foreach
    echo "</select>";

} // while

请帮助!!

1 个答案:

答案 0 :(得分:1)

您正在将中断行(<br>)连接到$foo变量,这就是比较失败的原因。你也不需要option标签内的这个断行,所以就这样摆脱它:

foreach($range as $time){
    $foo = date("H:i", $time);
    $selected = ($foo == $row['start_time']) ? 'selected="selected"' : '';
    echo "<option value='$foo'" . $selected . ">" . $foo . "</option>";
} // foreach

此外,根据您的评论,来自数据库的start_time也包含秒数,因此您需要相应地格式化时间戳:

$foo = date("H:i:s", $time);