从mysql中选择并使用复选框格式化它们并设置checked =“checked”属性

时间:2015-07-21 08:39:47

标签: php mysql

我有两个名为facilities的mysql表,另一个是user_facilities。在facilities表中存储了所有可用设施,user_facilities表具有属于一个用户的特定设施。

现在我需要从mysql中获取所有工具,并且需要使用每个工具的复选框进行格式化。在获取每个工具时,我需要将checked="checked"属性设置为属于当前用户的复选框。

我可以从mysql中选择所有设施:

$sql = "SELECT id, name
        FROM cuisines";

这就是我WHILE循环的样子。

$result = '';
// Fetch all the records:
while ($stmt->fetch()) {

    $result  = "<div class='checkbox'>\n";
    $result .= "    <label>\n";
    $result .= "        <input type='checkbox' name='facilities[]' value='{$id}'> {$name}\n";
    $result .= "    </label>\n";
    $result .= "</div>\n";

    $output[] = $result;    
}

有人能告诉我如何为这些属于当前用户的复选框添加'checked =“checked”属性吗?

这是我的user_facilities

CREATE TABLE IF NOT EXISTS user_facilities(
    user_id INT(4) UNSIGNED NOT NULL,
    facility_id INT(4) UNSIGNED NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

2 个答案:

答案 0 :(得分:1)

如果 user_facilities user_id 有一个 facility_id

$output = array();
// Fetch all the records:
while ($stmt->fetch()) {
    $check="";
    if($facility_id == $cuisines_id){ $check = "checked='checked'"}
    $result  = "<div class='checkbox'>\n";
    $result .= "    <label>\n";
    $result .= "        <input type='checkbox' name='facilities[]' value='{$id}' ".$chec."> {$name}\n";
    $result .= "    </label>\n";
    $result .= "</div>\n";

    $output[] = $result;    
}

假设您为用户提供了多个facility_id。

$facility_id=array(1,2,3,4,5);

foreach($facility_id as $facilites)
{
    $check="";
    if($facilites == $cuisines_id){ $check = "checked='checked'"}
    echo "<input type='checkbox' name='facilities[]' value='{$id}' ".$chec."> {$name}\n";
}

答案 1 :(得分:0)

获取当前用户ID,获取属于当前用户的设施$ id。

在While循环中创建IF并

if($faicilitityId == $id) {
 $result  = "<div class='checkbox' checked='checked'>\n";
 } esle {
 $result  = "<div class='checkbox'>\n";
}
相关问题