[英]Editing checkboxes data in php and updating the rows in mysql
在視圖中,我有一組復選框,作為較大表單的一部分,如下所示。
<input type = "checkbox" value = "1" name = "checkbox_array[]" /> Checkbox 1
<input type = "checkbox" value = "2" name = "checkbox_array[]" /> Checkbox 2
<input type = "checkbox" value = "3" name = "checkbox_array[]" /> Checkbox 3
<input type = "checkbox" value = "3" name = "checkbox_array[]" /> Checkbox 3
假設我選中復選框2和復選框4,然后單擊提交。 為了保存,我在控制器中通過如下所示的checkbox_array[]
循環。
$checkbox_array = $this -> input -> post('checkbox_array', TRUE)
<?php for($i=0;$i<count($checkbox_array);$i++){
$users = new User();
$users -> role_id = $checkbox_array[$i];
//Amongst other form data
$users -> save();
}?>
這會將數據庫中的數據保存為:
id role_id
1 2
2 4
使用相同的視圖,我打算編輯保存的數據。 所以說現在我要選中“復選框1”,取消選中“復選框2”,選中“復選框3”,保留復選框4。這樣,我打算在數據庫中包含以下內容。
id role_id
1 1
2 3
3 4
但是我不知所措,如何進行更新。 我一直在想從數據庫中獲取保存的數組,執行inarray()
搜索,然后插入不在保存的數組中的數據,從計算上我不知道這樣做有多有效。
有沒有可以用來實現此目的的mysql函數,例如replace()
,或者還有其他方法可以實現編輯?
謝謝。
在這種情況下,我通常要做的是首先刪除數據庫中與該表單有關的所有數據(針對特定用戶等),然后為復選框插入數據。 刪除符合條件的數據(尤其是如果刪除的WHERE位於索引列中)要比嘗試選擇並有選擇地刪除它們便宜得多。 更不用說它使代碼更加整潔,從長遠來看,出於維護原因,它有其好處。
為了更清楚一點,在索引上具有WHERE子句的DELETE比SELECT便宜,對於不應該存在的DELETE比對INSERT更便宜。
$checkbox1 = $_POST['checkbox_array'];
$selected_checkbox = "";
foreach ($checkbox1 as $checkbox1)
{
$selected_checkbox .= $checkbox1 . ", ";
}
$selected_checkbox = substr($selected_checkbox, 0, -2);
// your insert query here..
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.