php - filling in form fields from database values - php

I'm trying to "pre-fill" (not sure if there's a technical term for this) form fields with values that the user has previously entered in the database. For this example it's a City and State. When the user loads the page to edit options, these values (which they have previously entered) will automatically be in the text boxes.
<tr><td>City</td><td><input type="text" name="city" value="<? $city = "usercity"; echo $formValue->location('$city'); ?>"></td>
<td>State</td><td><input type="text" name="state" value="<? $state = "userstate"; echo $formValue->location('$state'); ?>"></td>
Is there any way to set a value based on the input (from the boxes above)? If it was something like function location($input) I would know how to, but when there's nothing in the parenthesis, is there any way to set a value?
function location(){
$userid = $_SESSION['userid'];
$server = 'localhost';
$user = 'root';
$password = '';
$connection = mysql_connect($server, $user, $password) or die(mysql_error());
mysql_select_db(testdb, $connection) or die(mysql_error());
$result = mysql_query("SELECT '$location' FROM userinfo WHERE userid = '$userid'");
$user_data = mysql_fetch_array($result);
if($location =='usercity'){
$userlocation = $user_data['usercity'];
return $userlocation;
}
else
$userlocation = $user_data['userstate'];
return $userlocation;
}

Instead of thinking about this from a global perspective think about the problem in it's context.
Your starting point (from the server perspective) is that an HTTP GET request has come in from a client for this page, or a client is returning to this page from after a POST request. In either case, the server has located the "resource" (the PHP script) that should handle this request and dispatched it by loading the PHP interpreter with the script file.
The context at this point is at the first line of the script; at the point where the interpreter has just finished parsing and started executing. Ask yourself: does the current request include an active session identifier? If it does have an active session, then check to see if the client has filled in this form before and if they have, substitute the default form values they've previously submitted for the normal form default values. If the client does not have an active session or has not used the form before then show a blank form with default values as needed.
Tip: Consider using this technique to debug your code. Pick a line in your code and place a mental "break point" at that place. Ask yourself: what is the context of this script at this point? What variables are defined? What is the server state? What is the client expecting? Once you have an answer to those questions, writing the code is simple.

From what I see in your code you have the variable in single quotes:
$city = "usercity"; echo $formValue->location('$city');
remove the single quotes, as it will pass '$city' as is, not the value of $city. Try
$city = "usercity"; echo $formValue->location($city);
to make it clearer:
$city = "usercity";
print ('$city'); // will print $city
print ($city); // will print usercity

My last few projects had forms all over the place and telling php to fill out the forms each time was a pain in the arse.
For my current project, I kept the input names the same as the mysql field names. Makes submitting and populating way easier.
When it comes to populating the forms, I use some ajax (jQuery used all over the project so using jquery's ajax() function;
FORM
<form>
<input name="field_one" type = "text" >
<input name="field_two" type = "text" >
<input type="button" value="Send">
</form>
I put a conditional statement at the top of the doc along the lines of:
<?php if($_POST['update']){
$query=mysql_query("SELECT * FROM table WHERE unique_id='$id' LIMIT 1");
echo json_encode(mysql_fetch_assoc($query));
exit;
} ?>
Lets say you have a list of items you want to be able to click on and edit (populate the form with it's corresponding data). I assign it a data- attribute and fill it with it's unique id, normally an AI PRIMARYKEY eg:
while($r=mysql_fetch_assoc($data)){
echo "<li data-unique_id=\"\">$r[name]<span class="edit">edit</span></li>";
?>
$('.edit').click(function(){
var toget = $(this).parent().data('unique_id');
$.ajax({
url:'here so it sends to itself',
data:'update='+toget,
success:function(data){
for (var key in data) {
if (data.hasOwnProperty(key)) {
$('input[name="'+key+'"]').each(function(){
$(this).val(data[key]);
});
}
}
}
});
There's a little more work required for <select>, <textarea>, checkboxes, but same general idea applies, (I threw in a couple of if statements, but it could probably be handled way better)
I could probably explain this better, but I hope you get the idea and i've been of some help.
FYI
my inserts are like...
foreach($_POST as $k=>$v){
$v=mysql_real_escape_string($v);
$fields.=" `$k`,";
$vals.=" '$v',";
}
$fields=substr($fields,0,strlen($fields)-1);//to get rid of the comma :)
$vals=substr($vals,0,strlen($vals)-1);//and again
mysql_query("INSERT INTO ($fields) VALUES ($vals)");

Related

Changing options in second drop down menu by user input in first drop down menu

Thanks for taking time to look at this.
I have two drop down menus. The first is a list of clients, the second is a list of projects.
All projects are tied to just one client, so I'd like for the code to get user input for the client, then read that value, and modify the PHP code to only print out the values in the second drop down menu that correspond to the client selected.
Here's some code. For the first drop down menu:
<div class="item">
<label for='clSel' id='tsClLabel'>Client:</label>
<select name='clSel' id='wClient' onChange="bGroup();">
<option></option>
<?php
$cQuery = "SELECT * FROM Clients ORDER BY Client_Name";
$cResult = mysql_query($cQuery);
while($cData = mysql_fetch_assoc($cResult)) {
echo '<option id="Cid" value="'.$cData['Id'].'">'.$cData['Client_Name'].'</option>';
}
?>
</select>
Here's my jQuery function to get the user-selected value from the first drop down:
<script>
function bGroup(){
val1 = $("#wClient").val();
// window.alert(val1);
// $('#div1').html(val1);
return val1;
}
</script>
And the code for the second drop down menu:
<label for='billGroupId'>Billing Group: </label>
<select name='billGroupId'>
<option value=''></option>
<?php
$sql = "SELECT * FROM Billing_Groups ORDER BY Client_Id, Name";
$sth=$dbh->prepare($sql);
$sth->execute();
while ($row = $sth->fetch())
{
if ($row['Name']!= ''){
echo "<option value='".$row['Id']."' > ".$row['Name']."</option>";
echo "<script> bGroup(); </script>"
}
}
?>
</select>
I know I need to include a WHERE statement in the second drop down menu
Basically Select * FROM Clients WHERE Client_ID == $jsVAR.
I already have the value I need in the var1 JavaScript variable. How can I get this little piece of data either read by PHP or sent to PHP via JS code?
Thanks!!
You can SELECT all records from the database, and then insert them to your page HTML using json_encode(). Something like that:
<?php
$sql = "SELECT * FROM Billing_Groups ORDER BY Client_Id, Name";
$sth=$dbh->prepare($sql);
$sth->execute();
$projectData = array();
while ($row = $sth->fetch())
{
if ($row['Name']!= ''){
$projectData[$row['Client_Id']][] = $row;
}
}
echo '<script type="text/javascript">var projects=', json_encode($projectData), ';</script>';
?>
Then, in your JS, you use the variable projects as an associative array (object), eg.:
<script type="text/javascript">
for (p in projects[clientId]) {
alert(projects[p].Name);
}
</script>
Tricky one,
You have a choice. One way is to use Ajax to grab the second level menu structure upon getting the first level choice, and populate the second level once that succeeds. That's likely to be a problem, as there will likely be some sort of network delay while that happens, of which you have no control (unless you are in a closed environment). So from a user point of view it could be counter intuitive and sluggish feeling, especially on a slow connection or shared hosting solution where timings can vary enormously.
The other way is to somehow pull all values possible and filter them (so hide the ones that don't apply) using jQuery, perhaps utilising classes or some other attribute as a method of filtering data. Using jQuery you can assign data to elements so you could also use that too. The second method may not be so good if there's a lot of data (can't tell from the scenario you've described). Looking at your second level code I don't see a WHERE condition so I'm not sure how the value from the first level is affecting that of the second level, so it's hard to know how to deal with that for this method.

SQL Query onsubmit - change existing results

Good morning everyone,
I have a page that performs a default connection to database, search and looped output of data to the page by applying a template for each result in the table using this code:
<?php
$result = mysqli_query($con,"SELECT * FROM XXX WHERE Type='ABCD';");
while($row = mysqli_fetch_array($result))
{
include('includes/template-1234.php');
}
mysqli_close($con);
?>
On the same page I have a simple HTML search box:
<div id="srch-form">
<form>
<input name="srch-box" type="text" id="srch-box" size="45" onClick="this.value='';" onFocus="this.select()" onBlur="this.value=!this.value?'Enter Product Name or SKU#':this.value;" value="Enter Product Name or SKU#">
<input type="submit" name="srch-btn" id="srch-btn" value="Search">
</form>
</div>
Because I am just learning PHP - how do I set this up so that the default action still occurs on page entry, but - onsubmit of something in the searchbox the data in the current page is replaced by the results of the submission? I guess I'm getting confused over the fact that since I have already assigned a value(s) to $result to get the default output, If the value of $result is changed by the search form, does PHP automatically refresh the page when the value of $result is changed? - Sorry if this is a simple thing.
First, you'll have to add an action (which file to refer when submitted) and preferably a method-type in your form-tag. You will also have to include value of $productName (given from server-side php) inside of your html (look at value attribute)
Do something like this:
html-form: (Examplefile: yourhtmlform.php)
Then in your php-file get value from a specific element like this:
<?php
//File querydb.php (example filename)
//Form is submitted and srch-box is set (only set when form is submitted)
if(isset($_POST['srch-box'])) {
$type = $_POST['srch-box']; //Get value of input-element
}
else {
$type = 'kingkong'; //Default type to search
}
$prepareQuery = mysqli_prepare($dbConnectionLink,"SELECT * FROM XXX WHERE Type=:type");
//...code to fetch results..
//You get a productName (or SKU) from db
if (isset($result['product_name'])) {
$productName = $result['product_name']; //or whatever your column is called
}
else {
$productName = '';
}
include('yourhtmlform.php'); //Observe that it must be php to echo out value of $productName in this included file
I noticed you didn't use prepared-statement. Look for more information on prepared statements here: http://www.php.net/manual/en/mysqli.prepare.php (use them!)
I hope this will help you somehow :-)

Form to form with PHP

I am trying to create a multi steps form where user will fill the form on page1.php and by submitting can go to page2.php to the next 'form'. What would be the easiest way?
Here is my code:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
?>
<form id="pdf" method="post">
New project name:<input type="text" name="pr_name" placeholder="new project name..."><br/>
New project end date:<input id="datepicker" type="text" name="pr_end" placeholder="yyyy-mm-dd..."><br/>
<textarea class="ckeditor" name="pagecontent" id="pagecontent"></textarea>
<?php
if ($_POST["pr_name"]!="")
{
// data collection
$prname = $_POST["pr_name"];
$prend = $_POST["pr_end"];
$prmenu = "pdf";
$prcontent = $_POST["pagecontent"];
//SQL INSERT with error checking for test
$stmt = $pdo->prepare("INSERT INTO projects (prname, enddate, sel, content) VALUES(?,?,?,?)");
if (!$stmt) echo "\nPDO::errorInfo():\n";
$stmt->execute(array($prname,$prend, $prmenu, $prcontent));
}
// somehow I need to check this
if (data inserted ok) {
header("Location: pr-pdf2.php");
}
}
$sbmt_caption = "continue ->";
?>
<input id="submitButton" name="submit_name" type="submit" value="<?php echo $sbmt_caption?>"/>
</form>
I have changed following Marc advise, but I don't know how to check if the SQL INSERT was OK.
Could give someone give me some hint on this?
thanks in advance
Andras
the solution as I could not answer to my question (timed out:):
Here is my final code, can be a little bit simple but it works and there are possibilities to check and upgrade later. Thanks to everyone especially Marc.
<form id="pdf" method="post" action="pr-pdf1.php">
New project name:<input type="text" name="pr_name" placeholder="new project name..."><br/>
Email subject:<input type="text" name="pr_subject" placeholder="must be filled..."><br/>
New project end date:<input id="datepicker" type="text" name="pr_end" placeholder="yyyy-mm-dd..."><br/>
<textarea class="ckeditor" name="pagecontent" id="pagecontent"></textarea>
<?php
include_once "ckeditor/ckeditor.php";
$CKEditor = new CKEditor();
$CKEditor->basePath = 'ckeditor/';
// Set global configuration (will be used by all instances of CKEditor).
$CKEditor->config['width'] = 600;
// Change default textarea attributes
$CKEditor->textareaAttributes = array(“cols” => 80, “rows” => 10);
$CKEditor->replace("pagecontent");
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
// data collection
$prname = $_POST["pr_name"];
$prsubject = $_POST["pr_subject"];
$prend = $_POST["pr_end"];
$prmenu = "pdf";
$prcontent = $_POST["pagecontent"];
//SQL INSERT with error checking for test
$stmt = $pdo->prepare("INSERT INTO projects (prname, subject, enddate, sel, content) VALUES(?,?,?,?,?)");
// error checking
if (!$stmt) echo "\nPDO::errorInfo():\n";
// SQL command check...
if ($stmt->execute(array($prname, $prsubject, $prend, $prmenu, $prcontent))){
header("Location: pr-pdf2.php");
}
else{
echo"Try again because of the SQL INSERT failing...";
};
}
$sbmt_caption = "continue ->";
?>
<input id="submitButton" name="submit_name" type="submit" value="<?php echo $sbmt_caption?>"/>
</form>
Add the attribute action with the url you'd like to go to. In this case it'd be
<form id="pdf" method="post" action="page2.php">
EDIT: i missed you saying this method doesn't work. What part of it doesn't work?
You should keep the action to the same script, so the POST action is still performed and then redirect with header("Location: page2.php"); when the processing is done.
A basic structure like this will do it:
form1.php:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
... process form data here ...
if (form data ok) {
... insert into database ...
}
if (data inserted ok) {
header("Location: form2.php");
}
}
?>
... display page #1 form here ...
And then the same basic structure for each subsequent page. Always submit the form back to the page it came from, and redirect to the next page if everything's ok.
You're probably better off separating the php code from the form. Put the php code in a file called submit.php, set the form action equal to submit.php, and then add the line header('Location: whateverurl.com'); to your code.
The easiest way is to post it to form2.php by giving the form the attribute action="page2.php". But there's a risk in that. It means that form2 must parse the posted data of form1. Also, if the data is wrong (verification) form1 must be shown instead of form2. This will make your code over complicated and creates dependencies between the two forms.
So the better solution (and quite easy as well) is to implement the post-redirect-get pattern.
You post to form1, verify all data and store it. If the data is ok, you redirect to form2. If the data is wrong, you just show form1 again.
Redirecting is done by a header:
// Officially you'll need a full url in this header, but relative paths
// are accepted by all browsers.
header('Location: form2.php');
Save already posted fields in hidden input fields, but don't forget to validate them every time user submits another step of the form as the user may change hidden inputs in source code.
<input type="hidden" name"some_name" value="submitted_value"/>
There are several ways handling the submitted data while jumping between steps.
You will find your reasons for /against writing data to session, database, whatever... after each step or not.
I did following approach:
The form includes always a complete set of input elements, but on page #1 the step-2-elements are hidden ... and other way round.
I built a 6-step-wizard this way. One large template, some JS /Ajax for validating input, additional hidden inputs that hold current step-ID and PHP deciding, which fields to show or hide.
The benfit in my opinion: Data can easily be saved completely, as soon as input is alright and complete. No garbage handling, if users abort after step 1.
I would store it all in a session array (or sub array)
a really rough example where I'm saving all the form names to an array (to be checked later of course):
<?
foreach($_POST as $k => $v){
$session['register'][$k]=$v;}
?>

Broad overview, flowchart on escaping user submitted content for html, javascript, and PHP

can anyone point me to good StackOverflow answers and other resources, including books, on escaping user submitted content for HTML, JavaScript, and PHP?
For example, say a user types information in a text box, and clicks a submit button. Then the text is written by JavaScript into a div on the page, and is also sent via GET to PHP, and by PHP is put into a MySQL database.
I am looking for a good, broad, but also detailed overview all the different types of escaping involved. A flowchart would help too!
Thanks!
Thanks! I'm looking for someone to make like a cheatsheet, with sections on 1) escaping for html display, 2) escaping for putting in a URL 3), sending the URL to PHP, 4) inserting data from the URL into a database. Each section should have 1) examples on potential problematic situations and characters that should be escaped, 2) examples on how to escape the characters, and 3) how to decode the characters if necessary later.
The benefit would be a one-stop source with many examples and solutions on escaping so that other users don't have to go through tons of different sites and answers and resources which have few examples and solutions. I think it would be great.
This chart looks pretty good so far
http://www.the-art-of-web.com/javascript/escape/
I'd always use "POST" for user data myself, not "GET", and the following discussion reflects that, but you'll still be able to use about 90% of what I say below either way. So here goes...
General rule: Don't "think ahead" when escaping data. Only make the immediately necessary transformation. Canonical example: Don't escape for HTML when doing a database insertion, since you'll end up with, for example, '&' turning into '&amp;' after a couple of round trips.
General rule: Use UTF-8 throughout. You'll be thankful for this the first time someone does a copy-paste from an email that has a unicode ellipsis in it. (You'd be surprised how often that happens.) Typical settings needed; this may vary with PHP/MySQL/HTML version:
PHP: php_value default_charset "UTF-8"
MySQL: Choose utf8 when creating the database.
HTML: <meta http-equiv="Content-type" content="text/html;charset=UTF-8"/>
General rule: There are only five places that unsanitized (though properly escaped) user data can go:
The value of a (properly-typed) database field (i.e. a UTF-8 text field or blob field).
The value of a PHP variable.
The value of a Javascript variable.
The value of an HTML form element's 'value' attribute.
The content of an HTML element's textNode child.
If you want to put user data in any other place, it must be sanitized. This is beyond the scope of the question, but in a typical case you might use a regular expression to replace anything that isn't an ASCII letter or number with an underscore. In cases where uniqueness matters, like a filename or an HTML 'id' attribute, additional work has to be done to make sure that the sanitized names are unique (e.g. make sure that the clash that happens when'a^b' and 'a&b' are both sanitized to 'a_b' is resolved). A typical solution looks something like:
filename = original_filename;
while(already_exists(filename)) {count++; filename = original_filename + count;}
And, finally, the meat of my response: The specific escape functions to use to move data to and from those Five Special Places where unmodified user data can go:
HTML form value attribute -> PHP $_POST variable: No escaping necessary.
PHP variable -> database field: PDO prepared statement:
$stmt = $db->prepare('insert into roundtrip (id, name) values (NULL, :data)');
$stmt->execute(array('data' => $_POST['name']));
Database field -> PHP variable: No escaping necessary, but use PDO prepared statement to escape query values:
$stmt = $db->prepare('select id, name from roundtrip where name = :data');
$stmt->execute(array('data' => $_POST['name'])); // User data needs escaping.
while ($result = $stmt->fetch()) {
echo $result['name']; // DB result doesn't.
}
PHP variable -> Javascript variable: json_encode:
var data = <?php echo json_encode(data); ?>;
PHP variable -> HTML textNode or form value: htmlspecialchars:
<div><?php echo htmlspecialchars(data); ?></div>
<input type="text" name="name" value="<?php echo htmlspecialchars(data); ?>"/>
Javascript <-> HTML textNode or form value: Browser's built-in textNode and .value attributes/functions:
data = source_div.textContent; // Firefox
data = source_div.innerText; // Other browsers
target_div.textContent = data; // Firefox
target_div.innerText = data; // Other browsers
// To/from form element.
data = source_form.value;
target_form.value = data;
// Append to element.
target_div.appendChild(document.createTextNode(data)); // All browsers
// jQuery textNode
data = $('#source_div_id').text();
$('#target_div_id').text(data);
// jQuery form value
data = $('#source_form_id').val();
$('#target_form_id').val(data);
Do a repeated round-trip test with a string like this to make sure it always goes through the whole HTML->PHP->DB->PHP->[Javascript->]HTML cycle exactly the same every time:
&ДЖäüöéè<script>…</script>™<i>bold</i>
Here's my script that tests escaping every which way; it obviously needs a database, a table with name 'roundtrip' and columns 'id' and 'name', and single row with id=1 to be created before running it:
<?php
$db = new PDO("mysql:host=$host;dbname=$dbname", $db_user, $db_password);
$stmt_insert = $db->prepare('
update
roundtrip
set
name = :name
where
id = 1
');
$stmt_select = $db->prepare('
select
name
from
roundtrip
where
id = 1
');
if ($_POST['do'] == 'edit') {
$stmt_insert->execute(array('name' => $_POST['name']));
}
$stmt_select->execute();
while ($result = $stmt_select->fetch()) {
$data = $result['name'];
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Roundtrip test</title>
<script type="text/javascript" src="/js/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
function copydiv() {
// Non-jquery:
//var source = document.getElementById('divdata');
//var target = document.getElementById('copydiv');
//if (typeof(source.textContent) != "undefined") {
// target.textContent = source.textContent;
//} else {
// target.innerText = source.innerText;
//}
// jquery:
$('#copydiv').text($('#divdata').text());
}
function copyform() {
// Non-jquery:
//var source = document.getElementById('formdata');
//var target1 = document.getElementById('copyform1');
//var target2 = document.getElementById('copyform2');
//if (typeof(source.textContent) != "undefined") {
// target1.textContent = source.value;
//} else {
// target1.innerText = source.value;
//}
//target2.value = source.value;
// jquery:
$('#copyform1').text($('#formdata').val());
$('#copyform2').val($('#formdata').val());
}
function copyjson() {
var data = <?php echo json_encode($data); ?>;
// Non-jquery:
//var target = document.getElementById('copyjson');
//if (typeof(target.textContent) != "undefined") {
// target.textContent = data;
//} else {
// target.innerText = data;
//}
// jquery:
$('#copyjson').text(data);
}
</script>
</head>
<body>
<div>Data: <span id="divdata"><?php echo htmlspecialchars($data); ?></span></div>
<div>JS div copy: <span id="copydiv"/></div>
<div>JS form copy: <span id="copyform1"/></div>
<div>JSON copy: <span id="copyjson"/></div>
<form method="POST">
<input type="hidden" name="do" value="edit"/>
<input type="text" name="name" id="formdata" value="<?php echo htmlspecialchars($data); ?>"/>
<input type="text" id="copyform2"/>
<input type="button" value="Copy div" onclick="copydiv();"/>
<input type="button" value="Copy form" onclick="copyform();"/>
<input type="button" value="Copy json" onclick="copyjson();"/>
<input type="submit"/>
</form>
</body>
</html>
To insert escaped things in a MySQL-Database using PHP (and other programming languages), there are the PreparedStatements.
If you want to directly display the users input in a div box and escape the input (so that HTML-Tags aren't interpreted i guess), you can check Point #4 in this article or use Google.
OWASP has an XSS Prevention Cheat Sheet which covers most (all?) of what you seem to be looking for. Does not address PHP directly.

Prevent duplicate record insert on manual page refresh

I have a problem which has only just surfaced itself.
I'm working in a MVC environment. The method names in my interface class match those of the request module and action i.e. ?module=test&action=action would result in a method called public function test_action() { }
In this particular problem, I have a form which submits to itself. If validation passes, a record is created and I then show the template of another module. This module expects a series of post variables as it is used in two modules.
The problem I'm having is that, if the user successfully passes the validation and attempts to F5 the page, another new record is created etc.
How can I prevent this from happening?
Normally I would header redirect after a successful insert but in this instance I can't.
I would take it a complete other way. I even find redirection an incorrect way of handling this, since changing locations is not meant to overcome logic/form troubles.
The correct solution is:
Add a unique hash to your form in a hidden input
Store the hash in a server-side session
When the form is send, validate the hidden input hash with the hash on your server
Only execute row insertion when the form validates correctly.
If you are working with Zend Framework, there is a Zend_Form_Element_Hash class for you.
Developer error:
You need to create a handler page which:
validating sent data
insert row
redirect user
You can / should re-direct to a new page after successful insertion.
As you are working in MVC, you can add a new controller that just calls the view you want to show.
Here is what I do it. This is working for me. Hope it can help anyone else.
//+++ start token +++
//This is to prevent duplicate entry on page reload (F5). 19. If I enter all values, press Record in journal and then press F5, the same values are recorded one more time. Need to prevent
// 3rd. $token_hash_from_input get value of input field name name="' .$_SESSION['token_hash'] .'"
$token_hash_from_input = $_SESSION['token_hash'];
//echo $token_hash_from_input .' token_hash_from_input<br>';
//echo $_POST[$token_hash_from_input] .' $_POST[$token_hash_from_input]<br>';
//var_dump($token_hash, $_POST);
// 4th. $_SESSION['token'] created/set in 1st. Then it as if goes around (at first to input field then after page reload returns here). However $_POST[$token_hash_from_input] is value received directly from input field. User click post and input field value is passed to $_POST[$token_hash_from_input]. Here I compare both.
if ( $_SESSION['token'] != htmlspecialchars($_POST[$token_hash_from_input]) ) {
$token_error .= 'yes';
//echo 'session token and token from input field are not the same <br> ';
}
else {
//echo 'session token is equal to post$token_hash)<br>';
}
// 1st. Create token and pass it to session
$token = sha1(uniqid(mt_rand(), true));
$_SESSION['token'] = $token;
//echo $_SESSION['token'] .' new $_SESSION[token]<br>';//after each page reload new token created. Then this token passed to input form (hidden field). value="' .$_SESSION['token'] .'"
// 2nd. Create token_hash and pass it to session. Token hash is to name input fields name and id. I may not use $token_hash and $_SESSION['token_hash']. Instead of this I can use name="token" and id="token".
$token_hash = sha1(uniqid($time_when_form_submitted .'token' .$_SERVER["REMOTE_ADDR"]));
//echo $token_hash .' $token_hash<br>';
$_SESSION['token_hash'] = $token_hash;
//echo $_SESSION['token_hash'] .' new SESSION$token_hash<br>';
// +++ end token +++
Input field like this
<input type="hidden" name="' .$_SESSION['token_hash'] .'" id="' .$_SESSION['token_hash'] .'" value="' .$_SESSION['token'] .'">
or
<input type="hidden" name="<?php echo $_SESSION['token_hash'] ?>" id="<?php echo $_SESSION['token_hash'] ?>" value="<?php echo $_SESSION['token'] ?>">
I suppose code can be improved (I have no good knowledge php etc)
"Normally I would header redirect after a successful insert but in this instance I can't."
are you facing some error in doing that?
If for whatever reason you can't redirect (Which sounds peculiar) you can use the 'same'
mechanism used for data validation to flush the forms after a successful insert.
But that's a really ugly way to go.
One of most common issue which many of the web developers face in their web applications, is that the duplicate records are inserted to the Database on page refresh. If the web page contains some text box and a button to submit the textbox data to the database. In that case when the user insert some data to the textbox and click on the submit button, it will save the record to the Database and then if the user refresh the web page immediately then the same record is again saved to the database as there is no unique keys that can be used to verify the existence of the data, so as to prevent the multiple insertion.
From this behavior we can definitely know that, on the page fresh the button click event is fired.
To avoid this problem we can try this method as discuss below.
On page load event save the date/time stamp in a session variable, when the page is first loaded, a Session variable is populated with the current date/time as follows:
*void Page_Load(Object sender, EventArgs e)
{
if(!IsPostBack)
{
Session["update"] = Server.UrlEncode(System.DateTime.Now.ToString());
}
}*
On the page's PreRender event, a ViewState variable is set to the value of the Session variable as follows:
void Page_PreRender(object obj,EventArgs e)
{
ViewState["update"] = Session["update"];
}
Then these two values are compared to each other immediately before the database INSERT command is run.
If they are equal, then the command is permitted to execute and the Session variable is updated with the current date/time, otherwise the command is bypassed as given below:
void btnSubmit_Click(object obj, EventArgs e)
{
string name = "";
string qualification = "";
if (Session["update"].ToString() == ViewState["update"].ToString())
{
if (txtName.Text != "" || txtName.Text != null)
{
name = txtName.Text.ToString();
}
if (txtQualification.Text != "" || txtQualification.Text != null)
{
qualification = txtQualification.Text.ToString();
}
//--- Insert data function should be execute here
string strSql = "INSERT INTO Testdata (Name,Qualification) VALUES ('" + name + "','" + qualification + "')";
SqlConnection ANConnection = new SqlConnection(ConnectionString);
ANConnection.Open();
SqlCommand ANCommand = new SqlCommand(strSql, ANConnection);
ANCommand.ExecuteNonQuery();
ANConnection.Close();
ANConnection.Dispose();
//--End of save data
lblMessage.Text = "Inserted Record Sucessfully
Session["update"] = Server.UrlEncode(System.DateTime.Now.ToString());
}
else
{
lblMessage.Text = "Failure – Due to Page Refresh";
txtName.Text = "";
txtQualification.Text = "";
}
}

Categories