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.
Related
Am using the same name for my table field and input text-box name in front end. Is it a good practice and is there any security issue here:
Table userdetails:
userdetails_firstname varchar(255)
userdetails_lastname varchar(255)
userdetails_username varchar(255)
userdetails_password varchar(255)
My html form:-
<input type="text" name = "userdetails_firstname"/>
<input type="text" name = "userdetails_lastname"/>
<input type="text" name = "userdetails_username"/>
<input type="text" name = "userdetails_password"/>
Thanks
There is nothing critical as long as you are using PDO and prepare() to avoid SQL injections.
I can't seem to figure this one out, nor how to start my query.
I have a form with different input field ID's
(customer_relationid, customer_brand, customer_goal, customer_floors, ....)
I have a mysql table with 3 columns (auto increment id, Key, Value)
The goal is to post all the info from the form row by row in mysql so that it results in this :
column id
this is just a auto increment, not important in this case
column KEY
relationid
brand
goal
floors
....
column VALUE
15
sony
music
3
.....
This is part of my form (the rest of the fields is the same):
<form id="calculator_form">
<fieldset id="generalInfo">
<legend>General Info</legend>
<h2>General Info</h2>
<label for="calculator_relationID">relationID:</label>
<input type="text" name="calculator_relationID" style="width:250px;" id="calculator_relationID" class="calculator_relationID">
<label for="calculator_brand">Brand:</label>
<input type="text" name="calculator_brand" style="width:250px;" id="calculator_brand" class="calculator_brand">
<label for="calculator_goal">Goal:</label>
<input type="text" name="calculator_goal" style="width:250px;" id="calculator_goal" class="calculator_goal">
<label for="calculator_floors">Floors:</label>
<input type="text" name="calculator_floors" style="width:250px;" id="calculator_floors" class="calculator_floors">
...
</fieldset>
How can I create the query as such so it knows it needs to insert it row by row for each form element?
Tnx in advance!
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.
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!
I have a variable number of fields in a form.
The number of text fields are defined by the user with a function in jquery, but the final code of the form (example) is this:
<form id='form_educ' name='form_educ' method='post' action='form/educ.php'>
<div id='educ'>
<input type='text' name='date1' id='date1'/>
<input type='text' name='date2' id='date2'/>
<input type='text' name='date3' id='date3'/>
<input type='text' name='date4' id='date4'/>
....
</div>
<input type='submit' name='form_educ' value='Refresh'/>
</form>
These text fields when added by the user is create a sql INSERT TO (in another file):
$date = clean($_GET['date']);
"INSERT INTO educ (index_of_form, date, email) VALUES('$index', '', '" .mysql_real_escape_string($_SESSION['SESS_EMAIL']). "')";
$date is date1, or date2, or date3 or date4 (example).
Now in the file educ.php I want to update all text fields in the mysql database.
Usually it is a
$example = clean($ _POST ['example']);
I can do an update in the table and is resolved.
But in my case how can I get all the values โโof the text field on the form and set the $_POST var if the number of fields is variable (could be date1, date2, date3, date4)?
I can think of no reason why form field name should be a unknown variable. Unless you're dealing with repeatable fields, in which case you would use an array like dates[], and you'd know what to expect in the process script.
For additional info see for example: http://www.web-design-talk.co.uk/58/adding-unlimited-form-fields-with-jquery-mysql/
Word of warning for future. When you make the field repeatable, allow users also to delete the fields they might have accidentally insertet. Watch out in the process script missing array keys (numerical index from 0โ10 might be missing some values if the user deleted some form fields before submitting). You can reset the array keys with the array_merge function. Missing keys is an issue if you have two arrays you are trying to add into database as syncronized.
Updated to answer the comment.
Sorry, I don't undestand your question. You don't necessarily have to use hidden field. What you need is a database structure to match your forms function: to support one to many relationship. After all you are inserting multiple dates that relate to one person, or some specific event type, or what ever. Lets assume one user wants to add his three favorite dates in the world. Your form's source code looks like:
<input type="text" name='dateLover' id='dateLover'/>
<input type="text" name="dates[]" id="date1" /> //you need a increasing variable for these id numbers (or dont't put the id at all)
<input type="text" name="dates[]" id="date2" />
<input type="text" name="dates[]" id="date3" />
In addition you could have more fields such as <input type="text" name="extra" />. In submitted $_POST array there would be variables and arrays like: $_POST['dateLover'], $_POST['date'][0], $_POST['date'][1], $_POST['date'][2], $_POST['extra']. You'd take the non-repeatable values straight out of the $_POST array but you need a foreach (or some else loop) to handle the dates array.
Your database has to contain two tables (structure simplified):
person: id, dateLover
date: id, dateLover FK to person.dateLover, date
In your process script you have to:
insert a new dateLover to person and use last_insert_id to get his id
use a foreach to insert new dates to table date (with a dateLover's id as FK)
This all is pretty well demonstrated in the link I supplied earlier. For now, it's hard to give an complete example without undestanding the actual problem.
Update 2.
You are serializing the form, not the div's. So your (dynamically generated) could look like this:
<form id="form_educ" name="form_educ" method="post" action="form/educ.php">
<div id="educ">
<div><!--This is for layout only-->
<input type="text" name="dates[]" id="date0" />
<input type="text" name="names[]" id="name0" />
</div>
<div>
<input type="text" name="dates[]" id="date1" />
<input type="text" name="names[]" id="name1" />
</div>
<div>
<input type="text" name="dates[]" id="date2" />
<input type="text" name="names[]" id="name2" />
</div>
</div>
<input type="submit" name="form_educ" value="Refresh" />
</form>โ
And in your process file you take these arrays from $_POST array and insert them into database maybe like this (with properly escaped and checked values of course...):
//dynamic part of the query
$qEnd = '';
$i = -1;
//this is static part of the query
$qBeginning = "INSERT INTO `date` (`id`, `date`, `name`) VALUES ";
foreach ($_POST['dates'] as $key => $date){
$i++;
$qValues[$i] = "(null, '{$date}', '{$_POST[names][$i]}')"; //never do this, always check values...
//value sets are concatenated one after another to the $qEnd
$qEnd .= $qValues . ',';
}
//combine the query parts and remove extra "," from the end
$q = $qBeginning . rtrim($qEnd, ',');
//now the (single) query ($q) is ready to be executed, echo it just for the fun of it
id should be auto increment field, or this kind of stuff doesn't work on the fly.
Again, this all should be clear in the jQuery link example so please read it carefully.
You should know all of the possible columns that could be updated before hand. Just check to see if those are set in the $_POST variable, then if they are append the insert or update statement with those values.
DANGER: Just looping on the $_POST variable looking at all params may end up inserting not database related POST fields into your insert statement and breaking.
Also when using these methods, be aware of SQL Injection, and use parameterized queries and never directly insert POST variable names or values into the SQL Statment.