开发者

PHP Saving Dynamic Radioboxes

开发者 https://www.devze.com 2023-01-22 20:36 出处:网络
Im having trouble tring to figure out how to save dynamic radio buttons. I have a project where i have to use radiobuttons instead of checkboxes.

Im having trouble tring to figure out how to save dynamic radio buttons.

I have a project where i have to use radiobuttons instead of checkboxes.

Basically, there is a database table with "roles" in it ... i.e administrator, user, etc etc etc and these are updateable but the user.

On a spe开发者_运维百科cific page, these get spit out with a radio button next to them, like so:

<input name="wfa" type="radio" id="wfa" class="radio" value="1" /><label for="wfa">administrator</label> 

These go on down the page, for as many entries there are in the database.

What i need to do is save the checked ones to the database, but being dynamic i cant save each value to a individual row ..... any help?

Someone mentioned serialize, i had a look at the php documentation but it didnt make much sense to me.

Cheers.


You would normally have (at least) three database tables: users, roles, and users_roles (a look-up table). The users table and roles table are self-explanatory. The users_roles table would probably have two columns: user_id and role_id.

So for example, they would look similar to as follows:

Table: users
id INT PRIMARY KEY
username VARCHAR
password VARCHAR
...

Table: roles
id INT PRIMARY KEY
name VARCHAR

Table: users_roles
user_id INT
role_id INT

With this database structure, you can then find out what roles a user has with a query like the following:

SELECT
    r.*
FROM
    users u, roles r, users_roles ur
WHERE
    u.id = ur.user_id
AND
    r.id = ur.role_id

This will then give you an array of roles assigned to the current user ID, which you can loop over and output a check box (a better solution in my opinion).

$res = mysql_query($sql);
while ($row = mysql_fetch_object($res)) {
    printf('<label for="role_%d">%s</label>', $row->id, $row->name);
    printf('<input type="checkbox" name="role[]" value="%1$d" id="role_%1$d" />', $row->id);
}

When you submit this, the checked check boxes will then be available as an array under $_POST['roles'], which you can loop over and insert into the users_roles table.


What i need to do is save the checked ones to the database, but being dynamic i cant save each value to a individual row ..... any help?

Why can't you maintain a reference table between roles and users with user_id and role_id? (Let's call this table users_roles_mm.)

When the form is submitted, delete all rows for the current user (user_id) and insert a row with a (user_id, role_id) pair for each checked input (role).

The idea here is that each table—roles and users—are dynamic, as is the reference between them. I.e., users_roles_mm is highly dynamic since it depends neither on the structure of the users table nor the roles table.

0

精彩评论

暂无评论...
验证码 换一张
取 消