duanchi4544 2013-10-24 12:13
浏览 36
已采纳

PHP / MySQL - 更新数据库中的复选框选择

Basically I have a form that contains several checkboxes (belonging to the same group), these are category selections.

When a user wants to UPDATE their selections, they can view this form - which already has their CURRENT selections ticked.

The user then changes their selections and submits the form. I now need to update these selections in the database. Here is the code I have at the moment:

// $old_selections contains an ARRAY of IDs - I use this to pre-select the checkboxes
$old_selections = Listing::getSelections();

if(isset($_POST['update']))
{
        // $_POST['selections'] is an ARRAY of posted IDs
        $new_selections = $_POST['selections'];

        foreach($new_selections as $selection)
        {
                // insert a new record using $selection
        }
}

So currently this ADDS the new selections to the database, but does not delete any existing ones. Ideally this should be a bit clever - rather than just deleting all existing entries, it should compare the two arrays and delete / insert as necessary.

Also if a user unticks all selections, then it would obviously need to delete all the existing entries.

What would be the most efficient way of achieving this?

  • 写回答

3条回答 默认 最新

  • dqmgjp5930 2013-10-24 12:59
    关注

    Complementing @ManZzup answer.

    When you submit the form, the update can be done like this:

    // You no longer need this
    // $old_selections = Listing::getSelections();
    
    if(isset($_POST['update']))
    {
        // $_POST['selections'] is an ARRAY of posted IDs
        $new_selections = $_POST['selections'];
    
        $list;
        foreach($new_selections as $selection)
        {
            $list .= $selection + ",";
        }
        $list = substr($list, 0, strlen($list));
    
        $query = "DELETE FROM tablename WHERE selection_id NOT IN (" . $list .") AND user_id = " . $id;
        mysqli_query($con, $query);
    
        foreach($new_selections as $selection)
        {
            $query = "INSERT INTO tablename VALUES (" . $id . "," . $selection . ")";
            mysqli_query($con, $query);
        }
    ...
    }
    

    Try something like this.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 python点云生成mesh精度不够怎么办
  • ¥15 QT C++ 鼠标键盘通信
  • ¥15 改进Yolov8时添加的注意力模块在task.py里检测不到
  • ¥50 高维数据处理方法求指导
  • ¥100 数字取证课程 关于FAT文件系统的操作
  • ¥15 如何使用js实现打印时每页设置统一的标题
  • ¥15 安装TIA PortalV15.1报错
  • ¥15 能把水桶搬到饮水机的机械设计
  • ¥15 Android Studio中如何把H5逻辑放在Assets 文件夹中以实现将h5代码打包为apk
  • ¥15 使用小程序wx.createWebAudioContext()开发节拍器