I have a form that has fields that auto populate with data from mysql table. Specifically two checkbox input fields for two types of roles; instructor
and contact
. I initially I stored values the values in the table as either 1
or 0
to signify true
or false
. A person can be one or the other, neither or both. When I try to display those values through a checkbox I am not getting a result. If the value of in the table for a particular role is 1
I want to have the checkbox checked
. I am getting no results.
DB query and display:
$db_select = $db_con->prepare("
SELECT a.name,
a.academy_id,
p.contact_role,
p.instructor_role
FROM academy a
LEFT JOIN person p ON a.academy_id = p.academy_id
WHERE a.academy_id = :id
");
if (!$db_select) return false;
if (!$db_select->execute(array(':id' => $id))) return false;
$results = $db_select->fetchAll(\PDO::FETCH_ASSOC);
if (empty($results)) return false;
$result = '';
foreach ($results as $value){
$result .= "<ul>";
$result .= "<li><input id=\"person_contact\" name=\"person_contact\" type=\"checkbox\"". $contact_role = $value2['contact_role'] == "1" ? "checked='checked'" : "" ." />Concact</li>";
$result .= "<li><input id=\"person_instructor\" name=\"person_instructor\" type=\"checkbox\"". $instructor_role = $value2['instructor_role'] == "1" ? "checked='checked'" : "" ."/>Instructor</li>";
$result .= "</ul>";
$s++;
}
Updated: What is $value2 ? you used $value in your foreach statement.
also change
$contact_role = $value2['contact_role'] == "checked"
to
$contact_role = $value['contact_role'] == "1"
and check again
Also for html messed up:
$result="";
$strChecked="";
foreach ($results as $value){
$result .= "<ul>";
if ($value2['contact_role'] == "1")
$strChecked = "checked='checked'";
$result .= "<li><input id='person_contact' name='person_contact' type='checkbox'". $strChecked ." />Concact</li>";
$result .= "<li><input id='person_instructor' name='person_instructor' type='checkbox'". $strChecked ."/>Instructor</li>";
$result .= "</ul>";
}
First, I think you have a problem with $value2 -- shouldn't that be just $value?
Second, unless you specify a "value" attribute on a checkbox input, it will return "On" during the get/post if checked, and will not return a value if unchecked. Try adding a value="1" to your checkbox, and then checking the value against "1".