Update page after successful insertion into MySQL table - php

I am making a page that has a bunch of fields that allows the user to enter in information and submit it to a database. This page is called 'add.php' I created a 'form' tag and had the information posted to another page called 'process.php' where the information is collected, then inserted into the database. I want the user to know whether it was successful or not, so I was wondering how to tell the user something specific on the 'add.php' page. like "insertion successful!" at the top of the page.
I thought of including the 'process.php' code in 'add.php', then calling the 'add.php' in the action of the form, but the code gets called the first time the page is loaded, which inserts a completely blank entry into the database.
Should I implement some sort of flag that is only set to true after the 'submit' button is clicked? Or is there another way to update the page and tell the user the status of the insertion?
I can paste the relevant code as needed. :)
Thanks!

Assuming that you are using the post method in your form and php, you can simply check if a post was made:
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
// form was posted, process and display output
}
else
{
// nothing was posted, normal get request, show form
}

just check if query worked well. If no exception was thrown, it mostly has, and the add appropriate message with output.
First you need to check and handle errors
try
{
}
catch(Exception $e){
header('Location:oldlocation.php?succ=0')
exit();
}
header('Location:oldlocation.php?succ=0')
exit();
If all goes well, you can also redirect to a new location(as shown in code). This has to be done properly, you may redirect back to the old location, with additional data like
oldlocation.php?succ=1;
If anything goes wrong redirect to
oldlocation.php?succ=0
Then fetch the succ using $_GET["succ"] and print appropriate message.
If you din get, comment.

Here's what I would do...
Keep your processing data in one file, and include the form file at the end
//add.php
//if the form is submitted make the database entry
if(isset($_POST['foo']) AND $_POST['foo'] != '')
{
//code to process form submission
$success = 'success!';
}
//include the form
include addform.php
in addform.php put your form. Include an 'isset' that is watching for $success to alert that the entry was successful
//addform.php
<?php if(isset($success)){ echo "<h2> Data successfully entered! </h2>";} ?>
<form action='' method='POST'>
<input type='text' name='foo' />
//etc
</form>
So once you submit the form, the code starts at the top of add.php - the 'isset' sees the $_POST submission, runs the form submission code and sets the success variable. Then, it includes the form page. The form page has an 'isset' that is watching for the success variable. When you first navigate to the page, or if you refresh, the add.php code will skip the first code block (the form submission stuff) and won't make a database submission or set the success variable.

Related

Page refresh causes form submission [duplicate]

This question already has answers here:
Avoid resending forms on php pages
(6 answers)
Closed 9 years ago.
I have a webpage that contains a form that uses the POST method and references the same page it is on for submission. I am using a PHP include file that contains an if statement that runs when the submit value is set. For some reason though, after one submission, every time you refresh the page it submits the form with the previously submitted data (The browser warns of this before refreshing the page). What causes this, and what could I be doing wrong?
This is expected. You should have the form submit to a handler that has a unique URL, whether it be a query string or a different URI. One solution (of many) would be to change your form action:
<form action="?action=submit" method="post">
<input type="hidden" name="action" value="submit" />
...
and then in the PHP script handle the form, then change the context back to a URL without the hidden query string
if (!empty($_POST['action']) && $_POST['action'] == 'submit') {
// do stuff
header('Location: '.$_SERVER['SCRIPT_NAME']);
die();
}
Note the query string is not actually present in $_POST but we keep it there so browsers don't consider it to be a redirect loop.
i had the same issue with one of my pages.
the reason is that when the browser warns you that it will submit the form again, that means it is going yo be the same exact thing when you click on a submit button.
I did 2 things to avoid it but i am sure there many other ways.
1. Do not let the page echo the form again after succesfull submission of the form.
mine was like this
<?php
if(!isset($_POST['submit'])) {
include(form.php);// you can modify this according to your needs.
} else {
//display your message about what happened with the form.
}
?>
with that approach, your page will not the contaion a form to submit HOWEVER this will not prevent it from submitting on refresh.
2. if the form is submitted create a contoller input that carries a value indication that the form is already submitted. for example , place this into your form:
<?=(isset($_POST['submit']))?"" :"<input type-"hidden" name="submit_stat" value="true" />" ; ?>
and when you process your form when it is submitted check it with your php and make the script act on that variable like this:
<?php
if($_POST['submit_stat']==true) {
//do not process the form here.
//stop your script
}
?>
Another thing you can do is redirect your page to another page other than the page that handles the form. i believe this is the safest one.
Another Way to prevent this is to move the Post Data to Session, redirect, collect Post back from Session and delete Session Post Data.
if(!empty($_POST) && empty($_FILES)){
// move post to session
// redirect to same url (don't forget possible get query)
}else{
// collect post from session
// unset post from session
}
Build this as default and you should never have problems with post data.
Only exceptions are File uploads. In this case redirect *after* post processing manualy.

How do i go about echoing back to a form from a form post action?

I have a form containing a textarea for inputing text into. The form also contains a submit button. After pressing the submit button it posts the text within the textarea into my php document. Within my php document the text is added to a database. Once it has been added to the database I would like it to echo back a response telling the user that it has added the text to the database successfully.
However, if i make it echo that response back to the home page, there is nowhere declared for it to display the echoed message. Has anyone got an idea of what i should be doing in order to get this working? Many Thanks.
Normally i wouldn't use a post straight from the form and i would use ajax and then display the data within a paragraph or something on it's return, however since the form is doing the post it's self i am not sure where to then declare where the response should show up.
The bellow displays my html form code and shows it's action to post to a php file.
<div id="userban2"><form id="bannable" action="/onlineusers.php" method="post"><p> Type username to ban bellow:</p>
<textarea name="banned" id="banned" maxlength="255"></textarea><br/>
<input type="submit" value="Send" class="extrabuttons" onclick="return false; preventDefault();">
<div id="cancelban" class="extrabuttons"><p> cancel</p></div>
</form>
However when in my php file i write ....
echo "the information has been added to the database successfully";
It might send the echo back however it isn't declared to display anywhere how can i change this to make it display the response within my form?
As requested return from my php
if(isset($_POST["banned"])){
$ban_name = $_POST["banned"];
bannedd($ban_name);
}
function bannedd($ban_name) {
$query1 = mysql_query("INSERT INTO banned_users (username,firstname,lastname,email,password,ip_address,sign_up_date,last_logged_in,about,sta rr,userpref) VALUES('$usernameb','$fnameb','$lnameb','$emailb','$passwordb','$ip_addressb','$sign_up_date b','$last_logged_inb','$aboutb','$starrb','$userprefb')") or die("Could not insert your informaion");
echo "This user has successfully been banned";
}
The form posts what is written in the form due to it having the action and method of post to my php. However should i then have any return i am not sure how i declare where the returned information should then show (The echoed message).
If I understand you correctly, your form is in some index.php file and sends the data to other file - onlineusers.php, and you want to display the message in the original page?
If this is the case, the most simple way I can think of is redirect back to the original page with a URL parameter, instead of echoing.
Do this at the end of onlineusers.php:
<?php
// insert text into DB ...
header("Location: index.php?result=ok");
?>
This redirects the browser back to the original page with the form. There you check if the status variable is set:
<html>
<head></head>
<body>
<?php if(isset($_GET["result"]) && $_GET["result"]=="ok") { ?>
<p>The information has been added to the database successfully</p>
<?php } ?>
<form> ... </form>
</body>
</html>
As you can probably see, you could set other results, such as "error" this way.
If you don't like the extra string in your URL, then create a cookie after processing the form in onlineusers.php and back at the original page, check if such cookie has been set. If you need more detail on that, let me know. And if you're asking something completely different, well, never mind :)
Your form is being submitted to /onlineusers.php
This is where you would want to add your echo statement.
If you require the info on the same page you technically return to the same page with the form action being $_SERVER['PHP_SELF'].
<form id="bannable" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Then you can put in a conditional statement prior to the load of your document, and include the PHP script.
<?php
$testVar = false;
$msg = '';
if($_POST) {
include '/onlineusers.php';
//... do something e.g post to database and return true.
}
if($testVar) {
$msg = 'Successful writing to DB!';
} ?>
<html>
<body>
<?php echo $msg; ?>
</body>
</html>
This will check to see if you have any post data, if you do, then it includes the script you specify. Maybe set $testVar to true if the writing to DB is successful, and then return $msg in your HTML.

returning from a form submit call to a .php file

I have a questionnaire in a form. In the end of it the submit button is pressed that is supposed to call a .php file that inserts data into a database through its action information and afterwards show the last page that contains something like "thank you for participating etc." via the onsubmit info.
problem is that the last page is shown before the .php file is shown which means it is visible only for like half a second and then the php script is carried out which ends up showing a blank page.
The php script works it inserts data into the questionnaire correctly so there should be no mistakes syntax-wise.
any ideas if I have to exit the cript or something and return to the .html file or what could be wrong?
on your opening form tag add action="submit.php"
then once it goes to that page when the submit button is hit add this to the bottom of that php page:
header("Location: successfull.html");
IT sounds like what youre doing is showing the message with Javascript via the onsubmit event - this happens before the request is even set to the server and the php script. Youd either need to do an ajax form submission and then display the message when the request completes or make the php script redirect to the success message page when it is done.
But this is all just speculation without seeing any code... you should post some :-)
Why not submit the form to process.php then process it:
if(isset($_POST)){
$name = $_POST['name'];
// etc etc
// if all error checks pass, then echo out - thanks for taking part in our survey!
}
What you're doing is submitting it, and it seems you're getting javascript to say 'thank you' but it is being submitted before this thank you message can be displayed - no harm in echoing this out on your .php page!!
Update
You mention about redirecting to a page afterwards, but this can be done by:
header("Location: where/to/go.php");
exit;
But you can't do this with the above (echoing out a success) since it will redirect straight away.
The way I deal with this is putting the html contents into the php file.
<?php
if (!isset($_POST["submit"])) { // if page is not submitted to itself echo the form
?>
<html>
<head>
<title>survey</title>
</head>
<body>
<form method="post" action="<?php echo $PHP_SELF;?>">
...... (your form) ......
<input type="submit" value="submit" name="submit"><br />
</form><br />
</body>
</html>
<?
}
else {
$db = new PDO('...');
$db->exec(...);
echo "Thank you!";
}
?>
A few ways you could accomplish that.
You could make the php file it submits send out the data for the "thank you for participating" page (if you're fine with simply going to another page).
Alternatively, if you want to stay on the same page but just show the "thank you" notification, I would use JavaScript to disable the default action (e.preventDefault(); in the event handler) for the "submit" button on the forum, then also use JavaScript to use AJAX to submit the data.
An example (using JQuery), which won't change your page and perform the submit in the background, and display the "thank you" when done, on the current page.
$("a#confirmSubmit").click(function(e) {
e.preventDefault(); // Prevents the submit button from changing pages
data = {
Name: $("input#Name").attr("value")
// Add other data here also
};
$.post("/page/to/submit/to.php", data, function(d) {
//Write the code here to show the "thank you" notification.
//It will show upon completion here.
});
});
If you want to check for errors with inserting into the DB, you could check the value of the data of the AJAX call, to conditionally show the error. You can then return the user to the exact same form they were already on, with all the data still there, and show them an error message.

Prevent user to use back button with warning or disable any insert

I have a form in page1.php which directs to page2.php from where the data from the form in page1.php is inserted into database. after successful insertion, page2.php displays a message and gives link to go to a third page.
The problem is when the user after the insertion hits the back button of the browser and clicks the form submit button, insertion is made again.
Is there any way so that after one insertion when the back button is pressed a message will be displayed showing that visiting the back-button is not allowed? Or in case it is allowed no insertion will take place on clicking the form submit button?
EDITED LATER TO ADD THIS PART:
okk let me tell in details. it is about an admin back end. the admin gives description text input for different products. He gives the input from page1.php and message is shown on page2.php that the description has been inserted into db. then there is another form below the message. It just asks whether the admin wishes to do more with description text. If yes, then clicking on the form submit button , he is taken to a page from where across some page(s) he is again taken to page1.php ( this time for another product), from there to page2.php and so on. btw i could use a normal page link instead of the form button link below the message on page2.php
The problem is, while the admin is on page2.php and hits the back button , he goes back to page1.php and from there if he hits on the form submit button, the data is inserted for the second time in a new row.
u may suggest to use 'IGNORE' with 'INSERT' command, but there are other columns in the row which may not get matched with those of another column while the description columns(admin inserts text data for this column ) may get matched.
1)Is ignore applicable in this case?
2)What should be the solution if duplicate entry is allowed for the database of the site?
thanks
hope it makes the whole thing clear.
Instead of giving link to a third page, redirect to the very same URI
this is quite handy method called POST/Redirect/GET:
here is a concise example of it:
<?php
if ($_SERVER['REQUEST_METHOD']=='POST') {
$err = array();
//performing all validations and raising corresponding errors
if (empty($_POST['name'])) $err[] = "Username field is required";
if (empty($_POST['text'])) $err[] = "Comments field is required";
if (!$err) {
//if no errors - saving data and redirect
header("Location: ".$_SERVER['PHP_SELF']);
exit;
} else {
// all field values should be escaped according to HTML standard
foreach ($_POST as $key => $val) {
$form[$key] = htmlspecialchars($val);
}
}
} else {
$form['name'] = $form['comments'] = '';
}
include 'form.tpl.php';
?>
Here you can see another example, concise yet powerful:
Separating Logic/Style in PHP properly
it's complete solution to display, add and edit database contents, exactly for admin purpose.
You should not display your message on page2.php.
Instead :
page2.php should deal with the data
when the data has been saved, page2.php should redirect to confirmation.php
And it's only confirmation.php which would display the message.
For more informations, take a look at the Post/Redirect/Get pattern.
Edit after the comment : but note that, in any case, you will never be able to prevent the user from re-submitting a form, if he really wants to...
The only solution you'll have is, when a form is submitted, to check in your database if the currently submitted data already exists -- and if it does, refuse to insert it again.
Of course, if the suer changes even a single letter in his input, it won't be the same data anymore...

Can I submit a form and add record to DB by only php in the same file without using Get/Post methods?

Say I have create a registration form. Now to add records into a DB, we send the data to another php file by POST method, where we do some validations and add a record. Is it possible to do it in the same file without sending and getting the data by POST/GET? If no, then why?
EDIT: Even sending to the same php file is SENDING and losing resource. I ask this question because I want to avoid the lost of time on sending by GET/POST and getting by the same Get/POST. And if it is not posible, I want to understand why PHP does not allow.
No. You always have to send data from the client to the server, there is no way around that.
If you dont want to reload the entire page the user is on, you could submit the data via AJAX to the php file responsible for processing it and adding the data. That way the user never leaves the page.
yes ofcourse.
just in your form "action" put
$_SERVER['PHP_SELF']
then in the beginning of your PHP page check if the $_POST is set or not
if(isset($_POST))
{
// actions to be taken after form submission
}
ofcourse you can add a hidden input tag for refining checks for the $_POST. eg in your form
<input type="hidden" name="formSubmit" value="yes" />
then your check should be like
if(isset($_POST['formSubmit']))
{
// actions to be taken after form submission
}
It's possible. For example:
<?php
if(true === isset($_POST['submit']) // check if submit-button was clicked
{
// do some validation here...
// If validation successes add record into db here...
}
else // no post data sent so output the form
{
// output the form here...
}
Yes it is possible set
action="same page"
in form tag.
you can access your all form attributes on same page.
Yes it is easy. The form can post back to its self. This is most easily done by not even specifying the value of action in the form tag.
<form method='POST'>
Then at the top of the page before any content is put on the page, include an if statement to check if the form was submitted.
if (isset ($_POST['post'])) { // 'post' is the name of the submit button
$error = false;
// Do validation
From there do validation and act according to the result.
If you have lots of validation to do, perhaps put that in another file and include it.
include "formValidation.php";
If all is well and all tests are passed use
if ($error === false) {
Header ("Location: confirmation.php");
exit;
}
}
If tests fail, stay on the page keeping all the post data, and display an error.
if (isset ($error) && !empty ($error)) {
echo "<div class='error'>$error</div>";
}

Categories