0

I am using a loop to create dynamic checkboxes as described here

Everything works as expected and I have successfully created a table with 2 columns: userid and preferences. Each checkbox has a unique preference value associated and If it is checked, then php stores it in a mysql database.

Now i need to repopulate the checkboxes if the user comes back on the page another day.

My idea (maybe not good enough..)

SELECT preference FROM Preference table WHERE UserId=CurrentUserId

and I can call the query result ---> $result[]

Now I got all the preferences of a certain user in a variable and I can make a loop with a IF condition when creating the dynamic checkboxes:

IF $result equals the current checkbox id then write checked

but I am not fully sure how to make it work and if it would work..any ideas?

1
  • Here's a quick and dirty solution. It's obviously not the best, but it gets the job done. $form = 'Your HTML content'; $form = str_replace("<input type=\"checkbox\" value=\"{$result}\" />", "<input type=\"checkbox\" value=\"{$result}\" checked />", $form); Commented Feb 21, 2012 at 4:18

1 Answer 1

2

It is exactly as you said.

  1. Get the preferences from database for the current online user ($clientId).

    $query = "SELECT preference FROM Preference WHERE userId = $clientId";
    $res = sql_query($query, $connection);
    while($userPreference = mysql_fetch_array($res))
      $userPreferences[$userPreference] = true;
    

    I will assume they have a unique identifier called preference.

  2. Iterate over all the preferences, checking against the selected $userPreferences from database.

    foreach($preferences as $preference) {
      $checked = $userPreferences[$preference] ? 'checked' : '';
      echo "<input type='checkbox' value='{$preference}' $checked />";
    }
    

Something like this should be enough to recreate the layout and choose user preferences.

Sign up to request clarification or add additional context in comments.

1 Comment

I tried to implement your code but I am a beginner and I didn't succeed.. I pasted my full code here: maybe you can understand better codepad.org/qluIjByA

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.