I have a PHP form with 4 text fields and 2 checkboxes. The checkboxes are "tags" that can be applied to the articles that are input using the text fields.
For example:
Information:
Title - Defining intransitive relationships of the migratory birds of South America
Author - Author. S. Wellington
Access Date - 19/06/2012
URL - http://www.wellington.org/articles/birds/def-int-rel-mig-bird-s-amer.pdf
Tags:
Birds[X] South America[X]
In this case both of the checkboxes would be checked, because the article pertains both to birds and South America.
I have a database with 3 tables in it:
articles: id - articletitle - articleorganization - articledate - articleurl
tags: id - tag_content
articles_tags: article_id - tag_id
Currently, my form can insert the article information into the articles table using:
mysql_query("INSERT INTO articles SET articletitle='$articletitle',
articleorganization='$articleorganization',
articledate='$articledate',
articleurl='$articleurl' ")
and then, I can use $article_id = mysql_insert_id();
to get the id that would be inserted into the articles_tags table.
But after that I am totally stumped.
I need to somehow loop over the checkboxes:
<input type="checkbox" name="articletags_birds" value="Birds" id="articletags_0" />
<input type="checkbox" name="articletags_southamerica" value="South America" id="articletags_1" />
but I have no idea how I should be doing that.
if ($_POST['articletags_birds'] == 'on')
{
mysql_query("INSERT INTO tags SET id='$article_id', tag_content='articletags_birds'");
}
Do the same for the other tags. If you have a very large number (5+), or want users to input their own tags, just do something like:
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'");
}
}
Note:
1.) There will be no POST sent if there is no checkbox selected!
2.) strpos will check if the tag starts with articletags_
3.) please ESCAPE the the queries! I've just shorthanded it all, but malicious PHP can be injected here
Comment if I'm unclear / if its still not working
I am not 100% what your problem is but:
Then when generating a form to update article i would get all tags from database and insert them in loop like this:
<input type="checkbox" name="tagArray[]" value = '$tagId' />$tagName
Then after submitting a form i would check in loop if any of these tags are set in post request and create new articles_tags like this:
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 } }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.