Form reviewing in HTML - php

I hope I'm not posting a duplicate question but I've looked around (and googled as well!) and nothing has given me the answer I'm looking for.
I have a form in HTML. When the user submits the form the values get stored with mysql under their user account for the site.
The issue is, I'd like the user to be able to go back and edit the form any time they like.
I could certainly just populate the form with values from php when the users review the form, but it gets tricky when I try to populate a file input field (and the file has been saved in mysql using the blob type). Not to mention that I'd like to do this as cleanly as possible.
Ideally it would be nice if there was a convenient module for reviewing forms that have already been submitted in JQuery per se.
Can anyone offer any advice? Thanks in advance!
Edit:
Here's a good example of what I mean - in chrome if I fill out a form and redirect to the next page after hitting submit, if I hit back I come back to the form and it's still filled out with the information I entered previously! Could I invoke this behaviour whenever I want to, as opposed to only when the user hits back?

You can't pre-fil an <input type="file" . . but surely when they come back to the form, they want to see the file they've uploaded .. this is what you mean right ..
So if its a picture, you could just do: <img src="loadpic.php?id=$var" />
If it's files they've uploaded, just list the file name / date and other data.. etc in some sort of list.
Then you could still show the <input type="file"> .. but with the label, 'add more pictures' or 'add another file'. .etc

Unless someone has a better way, at the moment I'm using a combination of 2 things:
1) Utilizing the $_SESSION variable
2) Setting the "name" attribute of every input in the form to the name of the field it corresponds to in the database.
This way I can loop through all the values dynamically instead of hardcoding them all in. Some input types (like file) are exceptional and will be handled on their own. Other that I can do something like this:
To insert into mysql:
$fields = array();
$values = array();
foreach ($_POST as $field => $value) {
$fields[] = $field;
$values[] = addslashes($value);
}
$fieldString = 'Table_Name('.implode(', ', $aFields).')';
$valueString = "VALUES('".implode("', '", $aValues)."')";
mysql_query("INSERT INTO $fieldString $valueString");
Reviewing the form is somewhat similar. I am using javascript to hook into document.onload. I need to pass javascript the records from mysql so that it may populate the form. Then it's a simple matter of getting elements by their name and assigning them their values that were passed from php.

The easiest way to do it and not have to go back to the database would be to store the values in a session.
<?php $_SESSION['myvalue'] = $inputvalue; ?>
On the html form use:
<input type="text" name="myName" value="<?php echo $_SESSION['inputvalue']; ?>" />
When completed don't forget to unset the session variable:
<?php session_start(); unset($_SESSION['myvalue']); ?>

Related

How to let PHP add another line for every form

I'm using Javascript to create more form fields, to be more specific I'm using jQuery append() to create copies of form fields I already have when a button is pressed.
For example there is an exercise form field, then when someone presses the + button they get another form field to add a second exercise. Now I have to get all these exercises into a PHP file, with no limit so someone could add a 1000 exercises and they would all get sent to my PHP.
I have it setup so jQuery gives them all a name tag with exercisex, the 2nd x being the number of the form field, so the original is exercise1, the second one exercise2, etc.
Now I submit the form and it gets send to another file, submitted.php.
In this file I have it setup for the original form field like this:
$exercise1 = $_POST['exercise1'];
and to put it in an array
$arrExercise = array (
>"exercise1" => $exercise1 );
What I'm looking is for a way that PHP automatically adds this:
$exercise2 = $_POST['exercise2'];
$exercise3 = $_POST['exercise3'];
and adds to the array
"exercise2" => $exercise2
"exercise3" => $exercise3
etc. for all the numbers ofcourse
Now obviously I can't add a unlimited amount into this myself so I was wondering how to get PHP to add them automatically according to how many were added.
I see the obvious risk that someone could spam it by adding a million exercises but that's not a concern for the environment this will be used in.
I tried a for loop but got stuck eventually:
I don't remember the exact code but I tried to add a variable, lets call it n, this variable would get a +1 everytime I pressed the + button so if n=1 at the start, pressing the button once makes it 2, then 3, then 4 etc. and then I got stuck thinking I'd still need to add an infinite amount of
$exercise + n = $_POST['exercise' + n];
if that would even work anyways.
Thanks for any help in advance.
I just solved a similar issue yesterday - here's how.....
The 'key' is to get the form names setup before sending to PHP.
(as you didn't give examples of your form, I will use mine for example - easy enough to port over to your project)
In my project, the user is allowed to add custom menu (nav bar) items as well as links under it, etc.
The way I solved it was to name things where PHP would get a nicely formed array in the $_POST;
<input type="text" name="menu1[Name]" value="">
<input required type="text" name="menu1[data][1][text]" value="">
<input required type="text" name="menu1[data][1][link]" value="">
'rinse/repeat' for all the form values that get added (replacing the '1' in the name with your variable) - you would also replace all 'menu1' with your 'exerciseX'
Now, put a 'Submit' button on the page;
<button type="button" id="custommenusave">Save Changes</button>
A bit of jQuery makes simple work of it....
$("#custommenusave").click(function () {
update_custom_menus();
});
function update_custom_menus() {
var form = $("#form_custom_menus");
$.post("../data/ajax.php", 'function=set_custom_menu&' + form.serialize(), function (data) {
form.submit();
});
}
PHP gets a nice array to work with (I've done a json_encode to make it simpler to see....)
{"menu1":{"Name":"'my menu #1'","data":{"1":{"text":"first","link":"https:\/\/example.com","options":"tab"},"2":{"text":"the second link","link":"http:\/\/example2.com","options":"tab"}}},"menu2":{"Name":"'menu #2!!!!'","data":{"1":{"text":"link in menu #2","link":"https:\/\/example.com","options":"tab"}}}
Then, pull your user's answers and work with them (of course, you should clean any data that comes from a user - no matter how much you 'trust' them!)
This should give you an idea of at least one way (with working code) that you can go.
name of your input should be an array so you can add multiple inputs by same name
<input required type="text" name="exercise[]">
$count = 1;
$finalArray = array();
if(is_array($_POST) && count($_POST) > 0){
foreach ($_POST as $value) {
$finalArray['exercise'.$count] = $value;
$count++;
}
}
print_r($finalArray);

filling the form in declared link

I have to declare an html link in my php file, i can do that in the following way
echo "<a href='razz.com'>Update</a>";
the link razz.com has a form fields(text type) in it, what i want to do is that when i open the link the form fields present in the link needs to be filled by the values that i declare in my initial php page.
the values of the form fields that needs to be filled are obtained from database.
How can i do that? Any tutorials or code snippet are appreciated.
Thank you.
Code snippet of what i am looking for:
a user fills form information which needs to go into database for storage:
the form is as follows:
<p>Title:<input type="text" name="title"/></p>
<p>Report No:<input type="text" name="rno"/></p>
<p>URL:<input type="text" name="url"/></p>
now after filling the form, the data will be stored in the database . A page with echo's successful with form information and a link to update the previously entered information will be displayed.
now again this update link contains the form structure , so instead of entering the information which was previously entered. the information already entered needs to be fetched and displayed in the form area.
You would need to use GET request parameters and the $_GET array on the page that is accepting the request to pass values to your link, but only if the http://razz.com/ index page actually accepts your URL parameters.
For instance (see the stuff and otherstuff GET keys in the URL):
echo "<a href='http://razz.com/?stuff=yes&otherstuff=yadayada'>Update</a>";
Then the razz.com index(.php):
$stuff = $_GET['stuff']; // with the link above, equal to yes
$otherstuff = $_GET['otherstuff']; // with the link above, equal to yadayada
echo "
<h2>$stuff</h2>
<p>I got $otherstuff.</p>
";
This would echo on razz.com/index(.php):
<h2>stuff</h2>
<p>I got yadayada.</p>
You could also use the $_POST array, but this would require more work and you would need to have a reason to do this (such as the data you're passing is transitory). You could do this by triggering a form, which you could also do a GET request with.
However, your question is not really that well worded. If you can provide more context and direction, that would help.

PHP: How can I take an input from the user, store it, and display it back?

I've been trying to create some php code that would let me
take input from a user using a text box. I want to then store
that input (probably like 7 characters long) and then display it
on a page in a list format ( eg
1
2
3
)
I've been at this for hours reading tutorials and what not but everything
I find only shows me the fwrite function and when I try to append I still
end up deleting data.
I would like the newest inputs to show up on top of the list if possible.
Can someone help me?
I am really frustrated and I know almost no php.. kind of playing around
with it and can't figure this out =/
I was thinking of storing the input from users in an array, then display the array..
But that doesn't work for me either.
So you want to have a form, let the users enter text, then display all the text entered by all the users, sort of like a wall or guestbook.
I'm presuming you've managed to fetch the user's input by looking at $_POST after the form submission. To store it in a file without overwriting the existing file contents the easiest way is file_put_contents with the special FILE_APPEND flag.
Lets say your HTML form has a textbox with name="newData". Then, in the form submission target script:
//store all user input in a file called data.txt in the current directory
$filename = "./data.txt" ;
$newData = $_POST['newData'] . "\n" ;
file_put_contents($filename, $newData, FILE_APPEND);
//now fetch all data and display it
$lines = file($filename) ;
echo '<ul>' ;
foreach ($lines as $line) {
echo "<li>$line</li>" ;
}
echo '</ul>' ;
Get started like that to see the basics in action and then you can look into:
filtering user input so that you don't store and display any nasty stuff
storing the data file outside the web root so that it's not accessible via the browser
prettifying the output list
If they're submitting the data via form, it will POST to the server; meaning you can use:
<form action="target.php" method="post">
<input type="text" name="username" value="" />
<input type="submit" name="submit value="Submit" />
</form>
for the markup, and then for the PHP (on target.php):
<?php
if (isset($_POST['submit']) { //to check if the form was submitted
$username= $_POST['username'];
}
?>
At this point you can then use <?php echo $username ?> anywhere you want to echo the data entered from the previous page.
I'm no PHP expert either (I recommend the Lynda.com training videos, "PHP & MySQL Essential Training" and "PHP & MySQL Beyond The Basics" with Kevin Skoglund) but maybe this helps.
As said above, you can use $_POST to get the data, however it is worth noting that if you are actually using this in a web application, you need to sanitize for XSS. You can do this quite simply with PHP's htmlspecialchars()
try this for taking input from user in php
$variablname = fgets(STDIN);
echo $variable;
file_put_contents('/path/to/file','contents',FILE_APPEND);

replace input field with data from mysql php

I created this layout of successive text input fields,
1- Enter data into empty fields
2- Click on button which submits to a php page that updates into database
Now the problem is that i want when i return to the main page again the empty field is replaced with data just added but there are still other empty fields to enter new data.
How can i establish that?
Thanks in advance.
You haven't given a lot of detail but here goes!
You could build your inputs like this:
<input type="text" name="age" value="<?php echo $age; ?>">
When the form first loads, it won't have values for variables like $age, so the input will appear empty. Have the form submit via POST to the same PHP file, run your validation checks, and if everything passes, insert into to your database. (Is it required that you write to the database at this point, or should it wait until the second section is filled out?)
You'll need to use some kind of conditional statement to display the second part of the form. Depending on how complex this is, or whether users will be returning later, you could:
Read the data back out of the
database to check for completeness,
and then display the second part.
Set a variable to track what stage of the form you're in, and based on that, display different sections to be completed.
If you have a way of tracking what stage of the process you're in, you could do something like this:
$formStage = 2;
function isReadOnly($formStage='')
{
if ($formStage == 2) {echo 'READONLY';}
}
and then in your HTML:
<INPUT NAME="realname" VALUE="Hi There" <?php isReadOnly($formStage)?>>

Is it better to implement a FORM and its ACTION with a single PHP file or two files?

I'm creating a FORM with PHP for an intranet webpage. Another PHP script is called by submitting the form.
Before anyone asks, the form does not allow any uploads, and although the values entered in the form find their way into an SQL query, I strip out everything but numbers.
I'm wondering if there would be a advantage in using the same PHP file for both the FORM and the ACTION?
Obviously, increased complexity is the penalty — ie, figuring out, when invoked, if the FORM is to be created, or if the SUBMIT button has been clicked — but what would be the benefits?
EDIT: Note, the PHP in 'submit' mode does not redisplay the form, it does something entirely different. This is the source of the complexity I was worried about.
The form is used to enter values which are checked against values in a DB, but there are no changes made to the DB.
I tend to find it more maintainable to have the php that creates the form separate from the php that is called by the form.
It will also reduce (though it isn't noticeable) one if statement to determine if this is a form request or filling in the form.
But, the problem is that unless you are going to take them to a new page, you will have to get the values back into the form which can be more complicated.
So, if you want to keep the values in the form, even after the form is processed, then leave the form processing logic at the beginning of the file, otherwise I would opt for maintainability and have them in two files.
In most case, I prefer that.
Keeping both together make the code more 'cohesive' as the code of accepting value (via form) is in the same php file (called it View and Control). To me this is an advantage.
However, the code that manipulate database should be separated in other file as it not the same as accepting value (called it a model library). This make it less-coupling as accepting and manipulation is separated. This decoupling will reduce the complexity you are worrying about.
Another advantage of is the URL. The users will see it as from the same page.
However, this is totally depends on your overall system metaphor and work flow. For example, it make better sense to the users that addBook.php handle book adding form and show that the adding has success or fail. Comparing that too having two addBook.php, addBookProcess.php.
What I am trying to say is that the flow of pages should be a more important factor to determine if you want to separate or combine them. Decoupling interface/logic code will helps you reduce the complexity if pages need to be combine into one php file.
Just my though.
Form is about user interface, action is about doing something with data.
The part of code that actually processes user input must certainly be separate from the form structure.
The form code must accept default values (or values previously entered and found to be invalid), error messages etc. It must have nothing to do with usage of successfully submitted form data.
If you allow user to change invalidated input, then you must have action URL the same as form.
If successful submission leads to something unrelated, then its URL must be different from that of the form. Basically, you must redirect user from the URL where the form got accepted to the next URL.
If you're doing AJAX, none of this applies.
It depends!
The upside to having them in one file is that it puts a single block of functionality into one place and allows you to handle form validation. The downside is increased complexity. It really starts to suck if you have the markup for both pages in one file.
I would suggest having 3 files - the main PHP handler, the template for the form and the template for the result page. The main PHP file would look something like this:
<?php
$error_message = "";
if ($form_submitted){
if ($form_validated){
include("inc-result.txt");
exit;
}else{
$error_message = "something went wrong!";
}
}
include("inc-form.txt");
?>
if validation fails, the logic drops you back to the form, where you can display the previously entered values, along with the relevant error message.
it does depend but in the long-term I would suggest separation of forms and business logic.
For quick projects I do understand the short-term gain of keeping it in the same page but you never know when the form you did needs to be added with features or needs to be turned to an ajax form. If you keep your logic separate from the form you would be ready for these changes quicker.
Well, mainly if you want to re-show the form to the users without losing data, then you can just write something like this:
<input type="text" name="myInput" value="<?php
echo htmlspecialchars(isset($_POST["myInput"]) ? $_POST["myInput"] : "");
?>">
Update: here is an example of this method:
<?php
$error = "";
$result = "";
$a = isset($_POST["a"]) ? $_POST["a"] : "";
$b = isset($_POST["b"]) ? $_POST["b"] : "";
if ($a !== "" && $b !== ""){
if (is_numeric($a) && is_numeric($b))
$result = sprintf("%s + %s = %s", $a, $b, $a + $b);
else
$error = "You must enter two numbers!";
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head><title>Sum numbers</title></head>
<body><form method="post" action="<?php print htmlentities($_SERVER["REQUEST_URI"]); ?>">
<p><strong>Enter two numbers to add them together.</strong></p>
<?php if ($error){ printf ("<p><em>%s</em></p>", htmlspecialchars($error)); } ?>
<p>
<input type="text" name="a" value="<?php print htmlspecialchars($a); ?>">
+
<input type="text" name="b" value="<?php print htmlspecialchars($b); ?>">
<input type="submit">
</p>
<?php if ($result){ printf("<p><strong>%s</strong></p>", htmlspecialchars($result)); } ?>
</form></body>
</html>
It seems like you should do 2 things:
1) create controller that steps in to see if you are doing an edit action or a display action
you already have the start of one at the top of your file there, just make it include "form.php" (your form) after it does it's business. So yes, make 2 files.
2) pull all that crappy formatting code up into the controller. Calculate all your values before the form is ever loaded. This includes running htmlspecialchars on all your form elements that need it. You can even loop through them to save lines of code:
i.e.
$cleanTheseVars = array ($a, $b, $c $error, $result);
array_walk($cleanTheseVars, 'htmlspecialchars' );

Categories