By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,950 Members | 989 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,950 IT Pros & Developers. It's quick & easy.

submit form entries to the database and redirect to the same page

P: 92
How do I submit form entries to the database and redirect to the same page, with the entries still display on the fields of the form? I really need help on this. Thanks.
Dec 7 '07 #1
Share this Question
Share on Google+
12 Replies


P: 41
How do I submit form entries to the database and redirect to the same page, with the entries still display on the fields of the form? I really need help on this. Thanks.
This is a really big topic and there are endless possibilities, but here is a little snippet for you.

Here is the basic idea.

1. use $_SERVER['PHP_SELF'] as the action of your script so that you come back to the same page when you submit the form.
2. if $_POST variables are set then process them put them in your database. then assign the $html['data'] variable the value you put into your database.
3. Then in the HTML section Line 22, the code will display the data depending if it is set or not.
4. If there are no $_POST variables set then, "probably" it is the first time the user has come to this page.

Assumptions: database used is mysql

Disclaimer: In no way does the following code deal with security issues and/or accessibility. However, this code should give you a good idea of what to do.

YOUR FORM PAGE WITH SOME PHP
[PHP]
<?php
//this is just a sample data validation function
function validdata($data) {
//check if the data meets your requirements
if (!ctype_alnum($data) {
//if not then return false
return false;
}
else {
return true;
}
}

//This function connects and returns a database that you specify
function db_connect ($server, $username, $password, $database) {

if (!$connection = mysql_connect($server, $username, $password)) {
//you may want to set a better error message for security purposes
die(mysql_error());
}
if ($db = mysql_select_db($database, $connection)) {
die(mysql_error());
}

return $db
}

$clean = array() //clean data container array
$html = array() //html container array
$mysql = array() //mysql container array

if ( isset($_POST['data']) ) {
if (!validdata($_POST['data'])) {
$html['errormessage'] = htmlentities("Please enter an alphanumeric string", ENT_QUOTES, "UTF-8");
}
else {
$clean['data'] = $_POST['data']
$mysql['data'] = mysql_real_escape_string($clean['data']);
$db = db_connect("server","username","password","mydatab ase");

$query = "INSERT INTO tablename (datacolumn) VALUES ('".$mysql['data']."')"
if (!$result = mysql_query($query)) {
die(mysql_error());
}
###########################################
##The code right below is what you should watch for
##This will be displayed in the form field
#############################################
$html['data'] = htmlentities($clean['data'], ENT_QUOTES, "UTF-8");
}
}
//else POST variables are not set then just display the form without data



?>
[/PHP]

HTML PART OF THE SAME DOCUMENT
[HTML]
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml" dir="ltr" >
<head>
<title>Sample Form</title>
<style type="text/css">
#boldred {
font-weight: bold;
color: red;
}

</style>
</head>
<!--Automatically focus the first form field-->
<body onload="document.myform.data.focus()">
<!--You can use post or get. I prefer POST. -->
<!--Notice that name is not valid XHTML strict in the form tag. It just makes things easier when you use javascript though -->

<form name="myform" id="myform" method="POST" action="<?php echo $_SERVER['PHP_SELF']?>">
<p id="boldred"><?php if (isset($html['errormessage'])) {echo $html['errormessage']}?></p>
<input type="text" name="data" id="data" tabindex="1"
<!--Here is your answer. Basically echo $html['data'] if it is set. If not then just leave the for field blank.-->
size="20" value="<?php if (isset($html['data'])) { echo $html['data'];}?>" />
<input type="submit" name="submitdata" id="submitdata" tabindex="2" value="Submit Data" />
</form>
</body>
</html>
[/HTML]
Dec 7 '07 #2

P: 92
First of all, thank you for responding to my post.

Though I was looking for a more simple solution, I'm pretty sure that your suggestion would work. It's just that I'm quite confused. I'm not really that of a hardcore php programmer. I know how to program in php but I haven't really mastered it. I haven't even used functions in my project before.

And the database that I use is mysql.

Do you have any other suggustion that is not too advanced?

Thanks.
Dec 7 '07 #3

P: 41
First of all, thank you for responding to my post.

Though I was looking for a more simple solution, I'm pretty sure that your suggestion would work. It's just that I'm quite confused. I'm not really that of a hardcore php programmer. I know how to program in php but I haven't really mastered it. I haven't even used functions in my project before.

And the database that I use is mysql.

Do you have any other suggustion that is not too advanced?

Thanks.
Sorry about that I got carried away.


here are the main points

1. In the action attribute of the <form> use this:
<form action="<?php $_SERVER['PHP_SELF']?>" id="myform" name="myform" method="POST">
When you submit this form, it will redirect back to itself.

2. When it redirects back to the same page, you then process the data, with the code on the top. If the $_POST variables don't exist then that means the user has come to your page for the first time.

3. After you have processed your data and entererd it into your mysql database put that same data into some variables. For my example I chose $html['data'].

4. <input type="text" name="data" id="data" tabindex="1" value="<?php if (isset($html['data'])) { echo $html['data'];}?>" />

This is the text field for the form in my example. Take a look at the value attribute. It contains a conditional statement

[PHP]
<?php
//if there is data to display then display it
if (isset($html['data'])) {
echo $html['data'];
}
//otherwise do nothing
?>
[/PHP]

Basically if you inserted data into mysql and put that same data into the $html['data'] variable then it should show up.
Dec 7 '07 #4

P: 41
Here is some simplified code.

1. I took out validation
2. I took out CSS and javascript to make it easier to read.

dataentry.php
[PHP]
//Check to see if you got some POST data from a form submission
if ( isset($_POST['data'])) {
//you really should validate your $_POST variables
//but I left validation out for simplicity

//insert data into mysql database

//set the html data variable to display the values in the submitted form
$html['data'] = $_POST['data']
}
//if you don't then just simply display the form

[/PHP]
dataentry.php
[HTML]
<html>
<head>
<title>My Data Entry</title>
</head>
<body>
<!--The action attribute is set to $_SERVER['PHP_SELF'] which is equivalent to the current page url dataentry.php-->
<form name="myform" id="myform" method="POST" action="<?php echo $_SERVER['PHP_SELF']?>" >
<!--Notice the value is that $html['data']. The same data you put into your data base. The code says if it exists then it will put it into the form field. If not then it will be blank.-->
<input type="text" value="<?php if (isset($html['data'])) {echo $html['data']}?>" size="20" name="data" id="data" />
<input type="submit" value="Submit Data" name="submitbutton" id="submitbutton" />
</form>
</body>
<html>
[/HTML]

hopefully this is the solution you are looking for
Dec 7 '07 #5

P: 92
Just what I was looking for. Thank you very much.

I have one more question.

I want to be able to redirect and insert to the database at the same time. When the user submits the form, the data gets inserted to the database and redirects to itself with the data present in the fields.

One more thing, I have more than a hundred fields in the different forms of the program that I'm developing.
Dec 7 '07 #6

P: 41
Just what I was looking for. Thank you very much.

I have one more question.

I want to be able to redirect and insert to the database at the same time. When the user submits the form, the data gets inserted to the database and redirects to itself with the data present in the fields.

One more thing, I have more than a hundred fields in the different forms of the program that I'm developing.
I'm not really understanding your question I think. Are you saying you want to

(A) redirect from a "DIFFERENT" page to the dataentry page and have data displayed,

or are you saying

(B)

1. Person comes to form
2. enters data and submits
3. comes back to the same page with data displayed in fields.

because if its (B) the code above will do exactly that.

Please elaborate. Maybe explain your system a little bit.
Dec 7 '07 #7

P: 92
I'm not really understanding your question I think. Are you saying you want to

(A) redirect from a "DIFFERENT" page to the dataentry page and have data displayed,

or are you saying

(B)

1. Person comes to form
2. enters data and submits
3. comes back to the same page with data displayed in fields.

because if its (B) the code above will do exactly that.

Please elaborate. Maybe explain your system a little bit.
Welll, here's how it goes:

1. The person comes to the form.
2. Enters data and submits.
3. The data gets inserted into the database. And comes back to the same page with data displayed in the fields.

It will redirect to the same page so that the user can still be able to edit/update whatever he needs to edit/update in the form before printing.
Dec 8 '07 #8

P: 92
I kinda understand your first post already. Although I don't understand how the data gets inserted into the database.
Dec 8 '07 #9

P: 92
Could somebody please respond to my post. I really need help on this.
Thanks.
Dec 10 '07 #10

P: 41
Could somebody please respond to my post. I really need help on this.
Thanks.
Ok let me elaborate further on this. The first piece of code, is pretty much solid. Not tested but in theory everything should work. The second piece of code took out a lot of things 1. validation of the data being input 2. the mysql stuff.

If you notice in the 2nd piece of code I put in a comment that says [color=#808080]//insert data into mysql database.[/color]
I left the mysql stuff to you, because in the initial example I posted it was hard to read with all the other stuff.

Here is a more detailed explanation.


USER EXPERIENCE

These are the steps that the user will go through.
1. The user will go to www.example.com/myform.php
2. User will enter the data.
3. User will press the submit button
4. Once the submit button is pressed the action attribute in the form tag you have will be activated and should be action="<?php $_SERVER["PHP_SELF"]?>" . This will redirect the user to the EXACT SAME PAGE THE USER WAS JUST ON. This is equivalent to action="myform.php". You can use either one; however, if you decide to change your myform.php filename to say... myentryform.php then $_SERVER["PHP_SELF"] will automatically match that. $_SERVER is a superglobal array about the user. In this case PHP_SELF simply refers to the page that the user is at. In this case it is myform.php. If you don't know what a superglobal is go to www.php.net or look up some tutorials.
5. The data the user submitted is now in the form fields

BACKGROUND

This is what actually happens

1. When the user comes to www.example.com/myform.php the first part of the code in my second example checks to see if the user submitted the form via the POST METHOD.

In the HTML if the method="POST" then after user submits the form all the form field data will be stored in another super global called $_POST. This is an associative array that stores all the form field data. Lets say for example you had an input tag <input name="data" id="data" type="text" size="20" />. The name or id is data right? When this form is posted the data is stored in the $_POST["data"]. The key association in the array is EXACTLY the same as the name or id of the input field.

2. Now if the user has come to myform.php for the first time, there is no POST data right? So if we go through the code I posted If (isset($_POST["data"])) should return false. In my code in there is no POST data, then there is no else clause in the if statement, thus NOTHING is processed.

3. Now think about this. What if the user submitted the form myform.php and it redirected to itself? If(isset($_POST["data"])) would then be TRUE right? This is probably what you are not understanding. What I have done is, I'm using the SAME PAGE to process AND display a form. If there is no POST data then just display the form. If there is POST data then process the form, insert it into mysql and display a form with the data.

4. Now here is the part where we process the data. Here is a sample code

WARNING: The mysql code I'm putting in here is very basic. There are better ways to do this now with PEAR, or mysqli. Please study the www.php.net documentation for further details.
[PHP]
<?php
if (isset($_POST["data"])) {
//set connection variables
$server = "myserver";
$user = "myuser";
$password = "password";

//connect to mysql
if (!$connection = mysql_connect($server, $user, $password)) {
die(mysql_error());
}

//select your database
if (!$database = mysql_select_db("mydatabase") {
die(mysql_error());
}

//PLEASE READ THIS PART CAREFULLY
// the EXACT same data is being put into $mysqldata and $html
//the POST data that is assigned to mysqldata is going into the database
//the POST data that is assigned to html["data"] will be in your html form.
$mysqldata = mysql_real_escape_string($_POST["data"]);
$html["data"] = $_POST["data"];


//form your sql query
$query = "INSERT INTO tablename (data) VALUES ({$mysqldata})"
//send your query
if (!$result = mysql_query($query)) {
die(mysql_error());
}

//close mysql connection. This is optional.
mysql_close();
}
//else if there is no post data just display the form
?>
<html>
<head>
<title>My Data Entry</title>
</head>
<body>
<!--The action attribute is set to $_SERVER['PHP_SELF'] which is equivalent to the current page url myform.php-->
<form name="myform" id="myform" method="POST" action="<?php echo $_SERVER['PHP_SELF']?>" >
<!--Notice the value is that $html['data']. The same data you put into your data base. The code says if it exists then it will put it into the form field. If not then it will be blank.-->
] <input type="text" value="<?php if (isset($html['data'])) {echo $html['data']}?>" size="20" name="data" id="data" />
<input type="submit" value="Submit Data" name="submitbutton" id="submitbutton" />
</form>
</body>
<html>
[/PHP]


the PHP and the HTML sections are in ONE PAGE myform.php or whatever you want it to be.

So once again.

1. User enters page for first time
2. The script checks for POST data
3. The POST is not available because the user has not done anything
4. Thus the script does nothing and the form is displayed.
5. User enters data
6. User presses submit button
7. User redirected to the same page.
8. BEFORE the page is displayed the script checks for POST variables.
9. The POST variables are now available so we enter the data into our mysql database.
10. The same POST data is set to another variable to display in the form.
11. After the data is sent the form is displayed with the data inside the form field.
Dec 10 '07 #11

P: 92
What if the user refreshes the page? Wouldn't it create duplicate entries in the database?
Dec 12 '07 #12

P: 41
What if the user refreshes the page? Wouldn't it create duplicate entries in the database?
Well think about it. If you refresh the page what will happen? There is no post data or data to enter into the database, so nothing will happen. The only way a person can submit data is by pressing the submit button. Why don't you try it first.

Also if you are worried about empty entries or invalid entries in your database then you HAVE TO validate your data as I explained in the very first example.

Making PHP do what you want isn't so difficult. Making PHP do exactly what you want takes some time.
Dec 12 '07 #13

Post your reply

Sign in to post your reply or Sign up for a free account.