我有两个名为 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/