2017-08-29 64 views
1

我需要幫助的checkboxe三個表之間的鏈接:PDO多個checkboxs插入或刪除

功能表(ID,標題,sulg)

職位表(ID,標題,蛞蝓,加)

posts_features(fea_id,POST_ID)

<input type="text" name="title" value="$post->title"> 
<input type="text" name="slug" value="$post->slug"> 
// importing all features 
<input type="checkbox" name="featuresid[]" value="$features->id"> 

如果選中(插入)如果不存在。

foreach ($_POST['featuresid'] as $choice) { 
$sql = $dbh->prepare("INSERT INTO posts_features (fea_id, post_id) VALUES ($choice, $id)"); 
$sql->execute(); 
} 

如果未覈對(刪除)posts_features

$sql = $dbh->prepare("delete form posts_features where ........ 

在此先感謝。

回答

1

一個複選框不$_POST,如果它不檢查,所以你不會有其特點,其中檢查辦法看到(從$_POST,反正)。

有幾種方法可以做到這一點,但沒有關於應用程序的更多信息,很難做出「最好」的建議,但這裏的一個方法將利用$_POST

添加一個額外的「隱藏」輸入,與相應的$features->id,成立了「現有」的條目:

注:我按照你的代碼約定上述證明這一點,即使他們顯然是僞代碼,將不起作用roperly。

<input type="checkbox" name="featuresid[]" value="$features->id"> 
<input type="hidden" name="existing[]" value="$features->id"> 

然後,你可以利用你的循環,像這樣:

foreach ($_POST['featuresid'] as $choice) { 
    $sql = $dbh->prepare("INSERT INTO posts_features (fea_id, post_id) VALUES ($choice, $id)"); 
    $sql->execute(); 
} 

// loop through ALL feature ids listed on the page 
foreach($_POST['existing'] AS $features_id) { 
    // if the feature id wasn't in the checkboxes, then delete 
    if (! in_array($features_id, $_POST['featuresid'])) { 
     $sql = $dbh->prepare("DELETE FROM posts_features WHERE ........"); 
    } 
} 
0

未勾選的複選框不會發送到PHP。所以當你迭代$_POST['featuresid']時,你只會看到被選中的複選框。這意味着要刪除未經檢查的特徵,實際上意味着刪除不在檢查組中的所有特徵。

首先,插入選定的功能:重要不要在循環中執行DB查詢;他們會真的減慢你的腳本。相反,insert all records at once。您還應該使用參數化查詢;絕對不要將用戶提供的值直接插入到數據庫查詢中!

插入後,刪除未選擇的這些功能:

DELETE FROM posts_features WHERE fea_id NOT IN (?, ?, ?, ?) 

每個?對應一個值$_POST['featuresid']

的選擇,如果你想PHP收到一個明確的選擇/每個功能的未選定值都是爲HTML中的每個功能使用「是/否」單選按鈕或下拉列表。

+0

尼斯的答案。我考慮過這一點,但擔心複選框列表可能只是所有post_features的一個子集,而不是完整的列表。 (例如,如果分頁)。 –