1

How do you select a dropdown value inside a foreach loop. The code below generate time with 30 minutes gap. I cannot able to select the value from mysql database.

$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

Please help!!

2
  • 'select a dropdown value inside a foreach loop' - what do you mean ? Commented Feb 25, 2018 at 16:20
  • @ishegg What do you mean break line. Commented Feb 25, 2018 at 16:26

1 Answer 1

1

You are concatenating a break line (<br>) to your $foo variable, which is why the comparison fails. You don't need this break line inside a option tag either, so just get rid of it:

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

Also, by your comments, the start_time coming from the database contains seconds as well, so you need to format your timestamps accordingly:

$foo = date("H:i:s", $time);
Sign up to request clarification or add additional context in comments.

7 Comments

It's still not selecting.
What's in $row['start_time'];? It works correctly here
Its a db col_name.
I know, I'm asking what's in it. What's the result of var_dump($row['start_time']);?
string(8) "10:00:00"
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.