Programatt
Programatt

Reputation: 836

php checkboxes from database issue

I have an array with 8 different application names in it. I loop through it and check a checkbox if a user has selected that option on previous login.

foreach($appsArray as $app){ 
    $query = " SELECT UK, SPAIN, FRANCE, BENELUX, GERMANY, SWEEDEN 
    FROM ".$app." 
    WHERE userid = ".$_SESSION['user']['id']; 

    $stmt = $db->prepare($query); 
    $result = $stmt->execute(); 
    $result = $stmt->fetchAll(); 

    echo("<td>".$app."</td> <td><center>
    <input type = 'checkbox' name=\"".$app."[]\"". 
    "value =\"".$app."UK\" checked=\"".$result[0]['UK']."\"/> ");

    $result=""; 
} 

This works to an extent, however- what options I select for the first app is reflected across all of them. This must be to do with the way foreach loops in php, however I'm not sure how.

Any advice would be truly appreciated.

EDIT: just to clarify, the options I pick for one application are reflected across all application check boxes. I want them to be independent.

Upvotes: 0

Views: 52

Answers (1)

Demonslay335
Demonslay335

Reputation: 796

I believe the issue could be more of how you are using the value for the checkbox. I've ran into some issues where the "checked" attribute doesn't like to work if you aren't using checked="checked". Try something like this.

$checked = $result[0]['UK'] ? ' checked="checked"' : '';

echo '<td>'.$app.'</td><td><center><input type="checkbox" name="'.$app.'[]"'. 
    ' value="'.$app.'UK"'.$checked.' /> ';

If this still doesn't work, make sure to do a var_dump or similar on the $result to make sure your query is working correctly.

Once you have this working, I would possibly see about combining those queries into one. I could help having 8 sub-queries hitting the database instead of 8 separate database calls.

Upvotes: 1

Related Questions