[英]How to Insert checked checkboxes and delete unchecked checkboxes using php and mysql?
[英]Using PHP/MySQL to loop through checked checkboxes and insert into database
我有一個帶有4個文本字段和2個復選框的PHP表單。 復選框是“標簽”,可以應用於使用文本字段輸入的文章。
例如:
信息:
標題 -定義南美候鳥的不及物的關系
作者 -作者。 惠靈頓
訪問日期 -19/06/2012
網址-http : //www.wellington.org/articles/birds/def-int-rel-mig-bird-s-amer.pdf
標簽:
鳥類[X]南美[X]
在這種情況下,將同時選中兩個復選框,因為該文章既涉及鳥類又涉及南美。
我有一個包含3個表的數據庫:
文章: id- 文章標題- 文章組織 - 文章日期 -articleurl
標簽: ID-tag_content
article_tags : article_id-tag_id
當前,我的表單可以使用以下命令將商品信息插入商品表中:
mysql_query("INSERT INTO articles SET articletitle='$articletitle',
articleorganization='$articleorganization',
articledate='$articledate',
articleurl='$articleurl' ")
然后,我可以使用$article_id = mysql_insert_id();
以獲得將插入到articles_tags表中的ID。
但是在那之后我完全陷入了困境。
我需要以某種方式遍歷復選框:
<input type="checkbox" name="articletags_birds" value="Birds" id="articletags_0" />
<input type="checkbox" name="articletags_southamerica" value="South America" id="articletags_1" />
但我不知道該怎么做。
if ($_POST['articletags_birds'] == 'on')
{
mysql_query("INSERT INTO tags SET id='$article_id', tag_content='articletags_birds'");
}
對其他標簽執行相同的操作。 如果您有一個非常大的數字(5+),或希望用戶輸入自己的標簽,請執行以下操作:
foreach ($_POST as $key=>$value)
{
if (strpos($key, 'articletags_') === 0) //identity, otherwise false will set this off
{
mysql_query("INSERT INTO tags SET id='$article_id', tag_content='$value'");
}
}
注意:
1.)如果未選中任何復選框,將不會發送POST!
2.)strpos將檢查標簽是否以articletags_開頭
3.)請逃避查詢! 我只是簡而言之,但是可以在這里注入惡意的PHP
如果我不清楚/如果仍然無法發表評論
我不是您問題的100%,而是:
然后,當生成表單以更新文章時,我將從數據庫中獲取所有標簽,並將其插入循環中,如下所示:
<input type="checkbox" name="tagArray[]" value = '$tagId' />$tagName
然后,在提交表單后,我將在循環中檢查是否在發布請求中設置了這些標簽中的任何標簽,並創建新的articles_tags,如下所示:
if(isset($_POST['tagArray'])) { $tagArray = $_POST['tagArray']; foreach($tagArray as $tagId) { mysql_query('...'); // insert new articles_tags with tag_id = $tagId and article_id =$article_id } }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.