0

I have about 32 checkboxes, each with their own name value (their names are numeric values: 1,2,3, etc). If I check one box, let's say checkbox 5, it will insert into the database along with checkbox 1, even though I didn't check checkbox 1.

I have been struggling to figure out why this is happening for the past hour...it's probably something simple and I'm just overlooking it.

I am using Laravel 3.

I'm excluding values: 3, 4, 14, 15 and 25 because they don't exist in my database.

$exclude = array(3,4,14,15,25);

for ($r = 1; $r <= 37; $r++)
{
    $exists = 0;
    if (in_array($r, $exclude)) continue;

    $hasRating = UserRating::where('uid', '=', $uid)->where('rid', '=', $r)->count();
    if($hasRating)
        $exists = 1;

    // rating doesn't exist and we're adding it
    if(Input::has($r) && !$exists)
    {
        $rating = new UserRating;
        $rating->uid = $uid;
        $rating->rid = $r;
        $rating->save();
    }

    // remove rating if unchecked
    if(!Input::has($r) && $exists)
        UserRating::where('rid', '=', $r)->where('uid', '=', $uid)->delete();
}

Here is the code for the checkboxes:

public static function showratings($uid, $rid, $rating)
{
    $check = UserRating::where('rid', '=', $rid)->where('uid', '=', $uid)->count();

    if($check)
    {
        $check = " checked";
        $name = "<strong>".$rating."</strong>";
    }
    else
    {
        $check = "";
        $name = $rating;
    } 

    echo "<input type=\"checkbox\" name=\"$rid\" $check /> $name";
}

1 Answer 1

1

You should not check whether the checkbox is set (by using Input::has) but give a value to the checkbox and check if the value is the same.

echo "<input type=\"checkbox\" name=\"$rid\" value="yes" $check /> $name";

// rating doesn't exist and we're adding it
if(Input::has($r) && Input::get($r) == 'yes' && !$exists)
{
    $rating = new UserRating;
    $rating->uid = $uid;
    $rating->rid = $r;
    $rating->save();
}

// remove rating if unchecked
if((!Input::has($r) || Input::get($r) != 'yes') && $exists)
    UserRating::where('rid', '=', $r)->where('uid', '=', $uid)->delete();
Sign up to request clarification or add additional context in comments.

Comments

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.