PHP结合HTML代码

时间:2014-12-12 16:18:22

标签: php html

我试图将一些PHP代码放在与HTML结合的代码中。

我有以下代码:

<?php
$result = mysqli_query($db,"SELECT * FROM klassen");
while($record = mysqli_fetch_array($result)) {
echo '<div class="groepitem"><input type="radio" [IN THIS PLACE] name="groep" value="' . $record['klasNaam'] . '">' . $record['klasNaam'] . '</div>';
}
?>

在[在这个地方]的地方,我想提出以下代码:

if($_SESSION['gebruikers_klasid'] == $record['klas_id']) {
echo 'checked';
}

我已多次尝试过,但我无法让它发挥作用。

4 个答案:

答案 0 :(得分:6)

您可以连接这样的三元运算符:

$result = mysqli_query($db, "SELECT * FROM klassen");
while($record = mysqli_fetch_array($result)) {
    echo '<div class="groepitem"><input type="radio" ' . ($_SESSION['gebruikers_klasid'] == $record['klas_id'] ? "checked" : "") . ' name="groep" value="' . $record['klasNaam'] . '">' . $record['klasNaam'] . '</div>';
}

答案 1 :(得分:0)

这应该有效

<?php

$result = mysqli_query($db,"SELECT * FROM klassen");

while($record = mysqli_fetch_array($result)) {
    if($_SESSION['gebruikers_klasid'] == $record['klas_id']) {
        $var = 'checked';
    }
    echo '<div class="groepitem"><input type="radio" '.$var.' name="groep" value="' . $record['klasNaam'] . '">' . $record['klasNaam'] . '</div>';
}

?>

编辑:现在会话检查它在循环内

答案 2 :(得分:0)

你可以通过许多不同的方式做到这一点,但如果你想要更清晰的HTML代码:

<?php

$result = mysqli_query($db,"SELECT * FROM klassen");

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

    if ($_SESSION['gebruikers_klasid'] == $record['klas_id']) {
        $checked = ' checked';
    } else {
        $checked = '';
    }

    echo '<div class="groepitem"><input type="radio"' . $checked . ' name="groep" value="' . $record['klasNaam'] . '">' . $record['klasNaam'] . '</div>';

}

?>

... OR

<?php

$result = mysqli_query($db,"SELECT * FROM klassen");

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

    $checked = ($_SESSION['gebruikers_klasid'] == $record['klas_id']) ? ' checked' : '';

    echo '<div class="groepitem"><input type="radio"' . $checked . ' name="groep" value="' . $record['klasNaam'] . '">' . $record['klasNaam'] . '</div>';

}

?>

答案 3 :(得分:0)

另一种方法是退出你的echo然后运行条件语句然后恢复你的回声...例如

<?php 
$result = mysqli_query($db,"SELECT * FROM klassen");   
while($record = mysqli_fetch_array($result)) { 
    echo '<div class="groepitem"><input type="radio" '; 
   if($_SESSION['gebruikers_klasid'] == $record['klas_id']) { echo 'checked'; }
    echo ' name="groep" value="' . $record['klasNaam'] . '">' . $record['klasNaam'] . '</div>'; 
} 
?>