Select from mysql and format them with checkboxes and set checked="checked" attribute

I have two mysql tables named facilities and other one is user_facilities. In facilities table have stored all available facilities and user_facilities table have particular facilities belong to one user.

Now I need to fetch all the facilities from mysql and need to format with checkbox for each facility. While fetching every facilities I need to set checked="checked" attribute to checkboxes which are belong to current user.

I can select all facility from mysql like this:

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

And this is how it looks my WHILE loop.

$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;    
}

Can anybody tell me how add ‘checked=”checked”` attribute for these checkboxes which are belong to current user?

This is my user_facilities table

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;


Source: php

Leave a Reply