Reputation: 1598
I have a table for documents and part of that is the docs being assigned to a category. The table for doc_list looks like this:
CREATE TABLE `doc_list` (
`doc_id` int(11) NOT NULL,
`doc_title` varchar(50) NOT NULL,
`doc_content` text NOT NULL,
`doc_created` datetime NOT NULL,
`doc_updated` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`user_id` int(11) NOT NULL,
`cat_no` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf16 AUTO_INCREMENT=122 ;
I am having to manually assign the cat_no (which is the category ID) but want it to be apart of my doc form submission:
<form action="actions/newDocAdd.php" method="post" id="rtf" name="">
<input type="text" name="doc_title" id="doc_title" required="required" placeholder="Document Title"/><br />
<?php
try{
$results = $dbh->query("SELECT * FROM cat_list ORDER BY cat_title ASC ");
}catch(Exception $e) {
echo $e->getMessage();
die();
}
$docs = $results->fetchAll(PDO::FETCH_ASSOC);
foreach($docs as $docs){
echo '
<input type="checkbox" name="cat_no" value="2" id="cat_no">'.$docs["cat_title"].'<br><br>
';}
?>
<textarea name="doc_content" id="doc_content" placeholder="Document Content" style="display: none;"></textarea>
<iframe name="editor" id="editor" style="width:100%; height: 600px;"></iframe>
<br><br>
<input onclick="formsubmit()" type="submit" value="Create Document" name="submit"/>
</form>
Now it shows me the categories and displays them as checkboxes but because some documents can be apart of more than one category i want to tick the boxes and submit them to the database.
Here is the category table:
CREATE TABLE `cat_list` (
`cat_id` int(11) NOT NULL,
`cat_title` varchar(32) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf16 AUTO_INCREMENT=5 ;
Upvotes: 0
Views: 797
Reputation: 35337
Assuming documents can have multiple categories:
First you need to group the checkboxes into an array. You can do this by using the same name with brackets.
<input type="checkbox" name="cat_no[]" value="1" />
<input type="checkbox" name="cat_no[]" value="2" />
<input type="checkbox" name="cat_no[]" value="3" />
Now when you submit the form, $_POST['cat_no']
will be an array containing the checked values.
For proper database normalization, you need a new table called something like 'doc_category'. In this table, you would have a composite key of 'doc_id' and 'cat_id':
doc_id | cat_id
1 | 1
1 | 2
1 | 3
This signifies that doc_id 1 belongs to the categories 1, 2, and 3.
The relationship from documents to categories is called a many-to-many relationship which in databases, requires a third table (intermediate).
Upvotes: 1