php - 从 mysql 中选择并用复选框格式化它们并设置选中的 ="checked"属性

标签 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;

最佳答案

如果您的user_facilities

中有一个facility_id 用于user_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";
}

关于php - 从 mysql 中选择并用复选框格式化它们并设置选中的 ="checked"属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31534167/

相关文章:

php - 如果在 Zend Framework 1.12 中进行循环,如何合并多个对象

php - 如何检查数据库中是否存在ID,否则将其插入数据库?

PHP MySQL 插入不起作用

php - 为什么第一次启动网站时没有 session ?

php - mysql查询选择不同记录的百分比

php - 如何检查 PHP 字符串作为查询参数是否有效

php - 使用主键获取行中的重复条目

PHP&MYSQL - 向数据库插入数据失败

php - 使用 PHP 将两个/多个图像上传到 MySQL

php - 分解为数组(键->值)