In short form, users have checkbox values stored in a MySQL database. I can loop through the database to display the VALUES (Skills_ID + Skills_Name) for each checkbox so the user can add their skills; however, I’m not able to populate these checkboxes with the default value marked “checked” for those skills already in the database.
A box full of karma for anyone who can help me get to bed tonight. 🙂
Here is my code:
function isChecked() {
$query = "select * FROM individual_skills WHERE Ind_ID = ".$_SESSION['Ind_ID']. "";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
// If value exists, set $valueExitsInDB to true
if (isset($row['Skills_ID'])) {
$valueExitsInDB="TRUE";
} else {
$valueExitsInDB="FALSE";
}
// if the value does exist, then we are writing 'checked' in the checkbox
if ($valueExitsInDB) {
return "checked";
} else {
return "";
}
} // END WHILE LOOP
} // END FUNCTION
And, my code within the checkbox loop looks like this (no need to burden you with reading the loop as I can safely pull the checkbox values to the output — just not the default value):
echo "<input type='checkbox' name='skills[]' value='$skill_ID' checked='isChecked()'>". $skillName ."";
So, you can see, I’m calling the function with: isChecked().
Any, and all help, very much appreciated.
There are a couple of problems with your code, assuming I understand what you are trying to do:
You are not actually calling the function
isChecked()as you believe; it is simply the string"isChecked()"being added to the output. If you checked the resulting HTML you would notice this. The line should read:As you notice above, you should pass the skill ID to the
isChecked()function. You should then check this row in the query, not *whether there is anySkills_IDset in the returned query. Otherwise you are checking whether any skill is defined for that individual! So your function should now read:A couple of side notes:
I am returning either a false or true value from the function. This is in line with the naming “is…” which will return a yes or no. The caller (the
echostatement) can then decide what to do with the returned value.You probably don’t have to hit the database 1000 times like you are doing now. If you change your initial query to include an
isCheckedcolumn you won’t need the function and additional queries in the first place.