lundi 20 avril 2015

Sql PHP Checkbox - How can you make it so the box determines the value?

I have a collection that if a checkbox is checked, the value is changed to 1 and it becomes a favorite and the checkbox stays even if the browser is refreshed. However, if the box is unchecked, it's status goes from one to 0 and it is no longer a favorite. There can only be 10.

How do I get to this from what my code is here? Let me know if I let something out that would help answer my question.

$username = 'gemi.com'/*$_SESSION['USERNAME']*/; 

if(isset($_POST['submit'])){//to run PHP script on submit
    if(!empty($_POST['favorites[]'])){
    // Loop to store and display values of individual checked checkbox.
        foreach($_POST['favorites[]'] as $selected){
            $query= "UPDATE u_collection SET fav = 0 WHERE username ='".$username."'"; 
            mysqli_query($db,$query);
        }
    } 
}


$query = 'SELECT gem, fav FROM u_collection WHERE username = "'.$username.'"'; 
$gems = [];
$result = mysqli_query($db,$query);
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $gem = new StdClass();
        $gem->name =  $row['gem'];
        $gem->fav =  $row['fav'];
        array_push($gems,$gem);
    }
}else{
echo 'Create a collection!';
} 

foreach($gems as $i){
    echo '<tr> 
    <th>'.$i->name.'</th> 
    <th><form action="collection.php" method="post">
    <input type="checkbox"'; 
    if($i -> fav){
        echo 'checked = "checked"';         
    }
    echo 'name="favorites[]" value='.$i->name.'></th></tr></form>'; 
}
?>
<th>
<input type='submit' name='submit' value='Submit'/>
</form>




Aucun commentaire:

Enregistrer un commentaire