简体   繁体   English

复选框插入数据库值,即使未选中

[英]Checkbox inserting database value even if not checked

I have about 32 checkboxes, each with their own name value (their names are numeric values: 1,2,3, etc). 我大约有32个复选框,每个复选框都有自己的名称值(它们的名称是数字值:1、2、3等)。 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. 如果我选中了一个复选框,比方说复选框5,即使我没有选中复选框1,它也会与复选框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. 我正在使用Laravel 3。

I'm excluding values: 3, 4, 14, 15 and 25 because they don't exist in my database. 我排除了值:3、4、14、15和25,因为它们在我的数据库中不存在。

$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";
}

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. 您不应检查复选框是否已设置(通过使用Input :: has),而应为复选框提供一个值并检查该值是否相同。

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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM