2012-06-20 101 views
0

我有一個PHP表單,包含4個文本字段和2個複選框。複選框是「標籤」,可應用於使用文本字段輸入的文章。使用PHP/MySQL循環選中的複選框並插入到數據庫中

例如:

信息:

標題 - 定義南美的候鳥

作者的不及關係 - 作者。 S.惠靈頓

訪問日期 - 19/06/2012

URL - http://www.wellington.org/articles/birds/def-int-rel-mig-bird-s-amer.pdf

標籤:

鳥[X]南美[X]

在在這種情況下,兩個複選框都會被檢查,因爲這篇文章適用於鳥類和南美洲。

我在這3個數據表的數據庫:

文章: ID - articletitle - articleorganization - articledate - articleurl

標籤: ID - tag_content

articles_tags: article_id --tag_id

目前,我的表單可以插入ar信息視察員將使用冠詞表:

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" /> 

,但我不知道我應該怎麼做。

+0

遍歷POST和比較索引名稱爲「文章標籤」。這樣您將循環所有articletags_ POST變量。 – cen

回答

2
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將檢查標籤是否以文章標籤開始_

3.)請將ESCAPE查詢!我剛剛缺兵少將這一切,但惡意PHP可以在這裏注入

評論,如果我不清楚/如果仍然沒有工作

1

我不是100%,你的問題是什麼 但:

  1. Offcourse我會產生一種形式更新文章 我會從數據庫中獲取所有標籤並插入環路這樣的時候保持標籤名稱數據庫
  2. 然後

    <input type="checkbox" name="tagArray[]" value = '$tagId' />$tagName 
    
  3. 然後提交表單,我會在循環 檢查,如果這些標籤在POST請求設置和 創造新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 
         }  
    } 
    
相關問題