【问题标题】:Checkbox inserting database value even if not checked插入数据库值的复选框,即使未选中
【发布时间】:2014-01-23 04:43:11
【问题描述】:

我有大约 32 个复选框,每个复选框都有自己的名称值(它们的名称是数值:1、2、3 等)。如果我选中一个框,比如说复选框 5,它将与复选框 1 一起插入到数据库中,即使我没有选中复选框 1。

在过去的一个小时里,我一直在努力弄清楚为什么会发生这种情况……这可能很简单,我只是忽略了它。

我正在使用 Laravel 3。

我排除了以下值: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();
}

这里是复选框的代码:

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

【问题讨论】:

    标签: php html forms checkbox laravel


    【解决方案1】:

    您不应该检查复选框是否已设置(通过使用 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();
    

    【讨论】:

      猜你喜欢
      • 2016-11-22
      • 1970-01-01
      • 2017-07-17
      • 1970-01-01
      • 2010-09-19
      相关资源
      最近更新 更多