Jump to content

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


thara

Recommended Posts

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;
Edited by thara
Link to comment
Share on other sites

You need to query your facility table LEFT JOINED to the user_facility table

SELECT f.facility_name
    , uf.user_id
FROM facility f
    LEFT JOIN user_facilty uf ON f.facily_id = uf.facility_id AND uf.user_id = $userID;

This will give results like

+---------------+---------------+
| facilty_name  | user_id       |
+---------------+---------------+
| air_con       | NULL          |
| wi-fi         | 1             |
| smoking area  | NULL          |
| bar           | 1             |
+---------------+---------------+


Loop through the results outputting the facility name and checkbox.
Check those boxes where restaurant_id is not null

air_con      [ ]
wi-fi        [X]
smoking area [ ]
bar          [X]
Edited by Barand
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.