Reputation: 740
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?
Upvotes: 0
Views: 913
Reputation: 23537
It is exactly as you said.
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
.
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.
Upvotes: 2