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

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.

Related

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!

How do I search my table for a form variable and add to the table if not found but increment the value by the user specified quantity if it is found?

I have the following form in my main page:
<left><h2><font color="ghostwhite">Enter Part</font></h2></left>
<form action="addpart.php" method="post">
<font color="ghostwhite">Date:&nbsp&nbsp&nbsp& &nbsp&nbsp</font> <input type="text" name="date" /><br>
<font color="ghostwhite">Part Number:&nbsp&nbsp&nbsp&nbsp&nbsp</font> <input type="text" name="partnum" /><br>
<font color="ghostwhite">Location:&nbsp&nbsp&nbsp&nbsp&nbsp</font> <input type="text" name="location" /><br>
<font color="ghostwhite">Quantity:&nbsp&nbsp&nbsp&nbsp&nbsp</font> <input type="text" name="quantity" /><br>
<input type="submit" />
</form>
I have the following php that I'm wanting to do the following:
Insert the $date entered by the user into the date column in the project database.
Insert the $partnumber entered by the user into the part_name column in the project database.
Insert the $location entered by the user into the location column in the project database.
Insert the $quantity entered by the user into the quantity column in the project database.
Here is the problem I'm having. I can't figure out how to search the part_name column for what the user entered and if it's not there enter it in with the quantity the user specified, but increment by the user specified amount if it is found.
I'm thinking it would be something like:
$dup = mysql_query("SELECT * FROM parts(part_name) WHERE VALUE($partnumber)
if ($dup)
{
mysql_query("UPDATE parts SET part_name = part_name + $quantity");
}
else
{
mysql_query("INSERT INTO parts (time, part_name, location, quantity) VALUES($date, $partnumber, $location, $quantity)");
}
Any help would be appreciated, thanks.
Have a look at:
http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
Should do what your asking
No comments on the html.

how to update sql table with a variable number of fields in the form php

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.

display same form multiple times in PHP

I have a table in database in which there is a column named roll_no, there are other four columns in the table. I am having a form to insert data into this table. I want to display this form x number of times, where x is number of distinct values of roll_no. That means if roll_no have 50 distinct values then the form will be displayed for 50 times on the same page. And in the form the roll_no field should be filled automatically with the value fetched from the database.
The other 4 fields are start_date, end_date, total_lectures, attended_lectures.
suppose start_date = 7th and end_date = 20 so there are total 13 lectures and out of which roll_no 1 attended 10 lectures and roll_no 2 attended 7 lectures and so on. The teachers fills the data like this in the form and then submit the form and data gets updated in the table. the combination of roll_no, start_date and end_date together serves as primary key.
If you have used phpmyadmin then you know that when we click on insert it shows two different forms to insert data.
I also want to accomplish something like this but the number of forms will be about 60 maximum.
I can't for the life of me figure out what you're trying to do, but if I understand you correctly, you want to print something as often as there are distinct values in the database.
(Pardon me, but I still use the old-school MySQL functions so if you're using the newer ones you might need to change this somewhat.)
$distinct_query = mysql_query("
SELECT DISTINCT row_no
FROM table_name
");
for ($i = 0; $i < mysql_num_rows($distinct_query); $i++) {
?>
All the stuff you want to print, where <?php print $i; ?> is the iteration of your form.<br />
<?php
}
Please note that this code is untested.
You could simply add a unique number to each form element as you ouput each sub-form
1. <input type="text" name="roll_no_1" ... />
<input type="text" name="start_date_1" ... />
etc...
2. <input type="text" name="roll_no_2" ... />
<input type="text" name="start_date_2" ... />
etc...
...
50. <input type="text" name="roll_no_50" ... />
<input type="text" name="start_date_50" ... />
etc...
or, if you trust the users to not mangle the form, you can use PHP's array syntax for form fields:
1. <input type="text" name="roll_no[]" ... />
<input type="text" name="start_date[]" ... />
2. <input type="text" name="roll_no[]" ... />
<input type="text" name="start_date_[]" ... />
...
50. <input type="text" name="roll_no[]" ... />
<input type="text" name="start_date[]" ... />
Either way works. The first has the benefits of guaranteeing that all the related fields have the same "subscript" identification within the name. The other one makes it simpler to simply do foreach ($_POST['roll_no'] as $idx => $val) { ... }

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