Insert multiple checkboxes into table column - php

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 ;

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).

Related

insert options with php and foreign key - not possible

I am building a simple web-database connection but when i assign a foreign key to my table than i am not able to insert data through html-php.
can anyone check my code and give me any suggestion/idea:
person table Primary key is ID
foreign key : KEY boardname (boardname),
KEY depname (depname)
board Table Primary key is boardname
deparment table Primary key is depname
Person table
CREATE TABLE IF NOT EXISTS `person` (
`id` int(5) NOT NULL AUTO_INCREMENT,
`name` varchar(10) NOT NULL,
`surname` varchar(10) NOT NULL,
`boardname` varchar(10) NOT NULL,
`bsdate` date NOT NULL,
`budate` date NOT NULL,
`depname` varchar(10) NOT NULL,
`desdate` date NOT NULL,
`deudate` date NOT NULL,
PRIMARY KEY (`id`),
KEY `boardname` (`boardname`),
KEY `depname` (`depname`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=16 ;
board Table
CREATE TABLE IF NOT EXISTS `board` (
`boardname` varchar(10) NOT NULL,
`boarddesc` text NOT NULL,
PRIMARY KEY (`boardname`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Depament table
CREATE TABLE IF NOT EXISTS `deparment` (
`depname` varchar(10) NOT NULL,
`depcomment` text NOT NULL,
PRIMARY KEY (`depname`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
now im using this simple script to insert data in the database and it not working i dont know why, but when i remove the foreign keys from person table it is working. any sugestion, i have to keep the foreign keys.
below is html php code:
HTML FORM
<body>
<h1>New Student</h1>
<form action="insert_student.php" method="post">
<table border="1">
<tr>
<td>ID</td>
<td><input type="text" name="id" maxlength="30" size="13"></td>
</tr>
<tr>
<tr>
<td>First Name</td>
<td><input type="text" name="name" maxlength="30" size="13"></td>
</tr>
<tr>
<td>Last Name</td>
<td> <input type="text" name="surname" maxlength="30" size="30"></td>
</tr>
<tr>
<td>Board Member From/Until</td>
<!--<td><input type="text" name="boardid" maxlength="7" size="7"></td>-->
<td><input type="date" name="bsdate" value="ICS" /><!--FSR-->
<input type="date" name="budate" value="Infor" />
</td>
</tr>
<tr>
<td>Department From/Until</td>
<!-- <td> <input type="text" name="depname" maxlength="30" size="30"></td>-->
<td><input type="date" name="desdate" value="ASE" />
<input type="date" name="deudate" value="WEB" />
</td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Register"></td>
</tr>
</table>
</form>
</body>
PHP Insert
<?php
# $db = new mysqli('localhost', 'e_kolori', 'kolori1515', 'e_color');
if (mysqli_connect_errno())
{
echo 'Error: Could not connect to database. Please try again later.';
exit;
}
$query = "INSERT INTO person (name, surname, bsdate, budate, desdate, deudate) VALUES
('$_POST[name]', '$_POST[surname]', '$_POST[bsdate]', '$_POST[budate]', '$_POST[desdate]', '$_POST[deudate]')";
$result = $db->query($query);
if ($result)
echo $db->affected_rows.' student inserted into database.';
$db->close();
?>
Your table specifies that all the fields are required.
Your insert statement is missing values for 'depname' and 'boardname'.
Also, (may not be relevant but worth checking) there must be the associated entries in your 'board' and 'department' tables before you insert a record that references them.
Yepp Correct by removing the Not Null option in php myadmin I am able to insert data from the form but when i updated the form with those two fields boardname and departmentname which are the foreign keys in my main table now i am not able to asign the boardname and depratmentname:
by removing null working fine
and this is how my form looks like:
Insert Form looks like
Should i make any change to my code somewhere i have no idea at the moment i have tried everything till now.
this is my new query in php:
$query = "INSERT INTO person (name, surname, boardname, bsdate, budate, depname, desdate, deudate) VALUES
('$_POST[name]', '$_POST[surname]', '$_POST[boardname], '$_POST[bsdate]', '$_POST[budate]', '$_POST[depname]', '$_POST[desdate]', '$_POST[deudate]')";

How to get add, edit, next & previous buttons on HTML form

I have an entry form to post data into a MySQL database (with a submit button) and it works fine. Now I want to have edit, next & previous buttons on it, to get next and previous record and also to edit them if needed.
I have searched on the internet but could not find a solution according to my requirement.
First of all, you should ensure that you have a column for the record ID that's an INTEGER, a PRIMARY KEY, and set to AUTOINCREMENT, let's call this `recordID`.
Let's take an example person table schema:
CREATE TABLE people (
recordID INTEGER PRIMARY KEY AUTOINCREMENT,
firstName VARCHAR(140) NOT NULL,
middleNames VARCHAR(250),
lastName VARCHAR(140) NOT NULL,
dateOfBirth DATE NOT NULL
);
To query the first record, we can do:
SELECT * FROM people WHERE recordID = 1;
Now to edit the record, we can do:
UPDATE people SET firstName="NewName" WHERE recordID = 1;
Next we build an HTML form to display/edit this data in.
<form action="#" method="post">
<input type="text" readonly="readonly" name="recordID" id="recordID" />
<input type="text" name="firstName" id="firstName" />
<input type="text" name="middleNames" id="middleNames" />
<input type="text" name="lastName" id="lastName" />
<input type="date" name="dateOfBirth" id="dateOfBirth" />
<input type="submit" />
</form>
Last of all you create some next and previous buttons to traverse through the records and populate the input fields, and then an edit button that sends the data to the server for it to update the database.
If you're feeling extravagant, you could use SQL's INSERT INTO ... ON DUPLICATE KEY UPDATE. E.g.:
INSERT INTO people (firstName, lastName, middleNames, dateOfBirth) VALUES (?, ?, ?, ?) ON DUPLICATE KEY UPDATE firstName="?", lastName="?", middleNames="?", dateOfBirth="?";
In order to do an "in-place edit", you could add a variable to the querystring.
For example, if you want to edit recordID = 3, you could have the URL as: http://yourserver.com/person/?id=3&edit.
On the serverside you can check for edit by using isset($_GET['edit']). If that returns true, than run your edit code and populate the fields/enable the edit functionality.

How to Store ID in Child Table of the Added String Value in PHP Table

I would like to ask how to insert an ID to the child table when I add a string value to the php table. Like for example:
I have a database called db and its corresponding tables:
CREATE TABLE IF NOT EXISTS `test1` (
`id1` int(11) NOT NULL AUTO_INCREMENT,
`fname` varchar(25) DEFAULT NULL,
PRIMARY KEY (`id1`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;
INSERT INTO `test1` (`id1`, `fname`) VALUES
(1, 'Mary');
-- --------------------------------------------------------
CREATE TABLE IF NOT EXISTS `test2` (
`id2` int(11) NOT NULL AUTO_INCREMENT,
`id1` int(11) DEFAULT NULL,
PRIMARY KEY (`id2`),
KEY `id1` (`id1`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
ALTER TABLE `test2`
ADD CONSTRAINT `test2_ibfk_1` FOREIGN KEY (`id1`) REFERENCES `test1` (`id1`);
Table test1 contains the existing data, and table test2 is the child table wherein added datas are to be stored from the php.
And also the php code, assume its connected to the database:
<body>
<div style="text-align: center">
<form action="test2.php" method="POST">
<?php
include('connect.php');
$query = "SELECT fname FROM test1";
$result = mysql_query($query);
?>
<select name="select1">
<?php while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
?>
<option value="<?php echo $line['fname']; ?>">
<?php echo $line['fname'];
?>
</option>
<?php }
?>
</select>
<input type="submit" value="Save" id="secret" />
</form>
<table border="1" width="200" id="sample" align="center">
<thead>
<tr>
enter code here
<th> ID </th>
<th> Name </th>
</tr>
</thead>
<tr class="record" height="100">
<td></td>
<td></td>
</tr>
</table>
</div>
</body>
test1.php
In my php code example, I have the dropdown menu containing data from the table test1 in the database and a button on the right side. If I select a data from the dropdown menu and save it, the data will be displayed to the php table and the id of the selected data will be stored in the child table test2 of the database. The problem is, how?
Please do help me with this problem.
Thank you.

How can I update and edit across two tables?

I have two MySQL tables that I created like this:
CREATE TABLE book(id INT UNSIGNED NOT NULL AUTO_INCREMENT KEY, title VARCHAR(256),
book_id INT, author VARCHAR(128), year INT, httplink VARCHAR(256)) ENGINE MyISAM;
and
CREATE TABLE excerpt(id INT UNSIGNED NOT NULL AUTO_INCREMENT KEY, book_id INT, excerpt_title
VARCHAR(256), year INT, measure VARCHAR(256), page VARCHAR(128)) ENGINE MyISAM;
So there's a table of books...and a table of excerpts from each book...they're linked by book_id. Each unique book has a book_id...and every excerpt from that book has the same book_id.
Now, I have a php form that allows to users to edit a entry after they've searched for it:
<p>Edit Record</p>
<form method="post">
<p>Title:
<input type="text" name="title" value="$n"></p>
<p>Author:
<input type="text" name="author" value="$e"></p>
<p>Year:
<input type="integer" name="year" value="$p"></p>
<p>Mirlyn link:
<input type="text" name="link" value="$l"></p>
<p>Excerpt name:
<input type="text" name="excerpt" value="$ex"></p>
<p>Page numbers
<input type="text" name="page" value="$s"></p>
<input type="hidden" name="id" value="$id">
<p><input type="submit" value="Update"/>
When the user hits the edit button next to the link, the following fields autopopulate with the record the user chose to edit: title, author, year.
If the user does not change the title, but changes (or doesn't change) the other fields, what is the correct MySQL statement to update the record? I believe I'd only have to update the 'excerpt' table.
BUT...if the user edits title...how do I manage that? I'd have to check if the title exists in the 'book' table. If it does, I'd have to change the book_id for the excerpt. If it doesn't, I'd have to add it to the 'book' table with a unique book_id and then change the record appropriately in the excerpt table. Help?
Thanks!

Establishing a "post ID" value for a comment leaving system

I am trying to attach a numerical "post ID" value to comments so that they can be retrieved from the database and displayed in the proper place. How do I establish this numerical value within my html form as something that gets sent to the script that inserts it into the database? I assume I need to use GET or POST but I don't understand how to use those to send anything except text entered by the user.
This is the form I am using to send the "name" and "comment" inputs:
<div class="comments">
<form action="foxpost.php" method="post">
<label for="name">Name</label><br>
<input id="name" name="name" type="text" /><br>
<label for="message">Comment</label><br>
<textarea class="message" id="message" name="message"></textarea><br><br>
<input type="Submit" value="Post Comment" />
</form>
</div>
Since you tagged this question with PHP, I'm guessing thats the language your using for your back-end. Another assumption I'm making is that your actually formatting your request querystring with the postID, something like "http://example.com/posts.php?postID=1212", notice the postID in the querystring, you just pass that on, like this:
<div class="comments">
<form action="foxpost.php?postID=<%= $_GET['postID'] %>" method="post">
<label for="name">Name</label><br>
<input id="name" name="name" type="text" /><br>
<label for="message">Comment</label><br>
<textarea class="message" id="message" name="message"></textarea><br><br>
<input type="Submit" value="Post Comment" />
</form>
</div>
Using
<%= $_GET['postID'] %>
will simply echo the postID from the querystring straight into the HTML, or you could assign it to a variable.
If you are using mysql you don't need to create it, mysql can auto-create it when you insert a new post.
For example we could create a table
CREATE TABLE `student` (
`student_id` INT( 3 ) NOT NULL AUTO_INCREMENT,
`name` VARCHAR( 25 ) NOT NULL ,
`email` VARCHAR( 50 ) NOT NULL ,
UNIQUE ( `student_id` )
);
And then use the following query
INSERT INTO `student` ( `name` , `email` ) VALUES ( 'john', 'email' );
As you can see the id is not specified in the query, but the field has the AUTO_INCREMENT attribute. When you insert a student without an id it will get the highest id and add one. So if you have the empty table and run the above insert query, you will get 3 rows with id 1,2 and 3.
More in the mysql manual http://dev.mysql.com/doc/refman/5.0/en/example-auto-increment.html
p.s. if you are using a different database please specify wich one.
--- EDIT 1 ---
might have misread the question very badly (it's past midnight but that's not an excuse)
You have a few options if you want to pass
1. a hiddent field, that was mention here
2. a $_GET['postid'] from something like comment.php?postid=13 if you add comments from another page
3. both
BUT don't forget, before adding the comment that the post exists.
... might i suggest using the akismet library to cut down on spam ?
http://www.achingbrain.net/stuff/php/akismet
You can get a key for free when you register at wordpress.com
Put the id in a hidden field in your form:
<input type="hidden" name="post_id" value="id_goes_here" />
I would suggest to not have the ID as part of the form and just use your databases AUTO_INCREMENT feature.

Categories