繁体   English   中英

使用PHP / 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%,而是:

  1. 当然,我会将标记名称保留在数据库中
  2. 然后,当生成表单以更新文章时,我将从数据库中获取所有标签,并将其插入循环中,如下所示:

     <input type="checkbox" name="tagArray[]" value = '$tagId' />$tagName 
  3. 然后,在提交表单后,我将在循环中检查是否在发布请求中设置了这些标签中的任何标签,并创建新的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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM