I have a multi-step form which asks the subscriber to check their details before proceeding with the renewal process.
What I want to do is check if the form has been modified from its pre-filled values (extracted from a Web Service) and then write it to my own local MySQL database. This should only happen if the values have been modified from the original.
I know I can do this by using the == operator but I was wondering if there was a more efficient way to do this?
You can do it with (multidimensional) arrays. Name the form/service variables carefully then compare them upon submit with array_diff which tells you which values has been modified.
Because you said this is a multi-step form, of course you can collect previously submitted values in a $_SESSION variable too.
You could do this with javascript on client side:
HTML
<input type="text" id="username">
Javascript
var input = $('#username');
if (input.defaultValue != input.value) {
//Do stuff if different
} else {
//Do stuff if equal
}
Related
I have a form that has 3 steps. I use SESSIONS to keep values from step to step. When I open the same form in another tab and complete the first step, this immediately replaces the Session values from the other form.
So how can I create sessions with field values that are attached to a specific form? I need to avoid Session conflicts.
If the forms are indeed different, then put it in a multi-dimensional array:
$_SESSION['register']['field1']=$_POST['field1'];
$_SESSION['contact']['field1']=$_POST['field1'];
If it is the same form and it is just a new tab, you can either check if the value was set before and ignore it, set a flag to say there is a form submission in progress, or entirely delete the old session values so the new form in the new tab has no values attached.
I use this function to handle form input:
function Hold_Form_Input($formname)
{
$FormPost = array();
foreach ($_POST as $key => $entry)
{
$FormPost[$key]= $entry;
}
$_SESSION[$formname]= $FormPost;
}
And I pass the form name in with a hidden input.
I have several input fields and I want it to submit when there is only one field with entered values and the others are empty (updating user data). I worked by now with isset() but this only sends the form when every field is filledout:
if (isset
($_POST['submit']) AND
($_POST['firstname']) AND
($_POST['lastname']) AND
($_POST['address']) AND
($_POST['ZIP']) AND
($_POST['phonenumber']) AND
($_POST['mail']) AND
($_POST['group'])
)
Later on I check in the mail template (another file) if there is a value and wheter to show it in the mail or not:
{if !empty($firstname)}{translate text='First Name'}: {$firstname|escape} {/if}
Is my idea ok or is there an easier way to solve this?
The first if statement is in conflict with your requirements; you are requiring all fields to be filled in by using the AND operation - use OR and it will work with any single field value.
Validation should/could also be performed on the page itself by using javascript as Matt recommends.
To ensure that only one field is set do the following you could count the number of entries in _POST
if(count($_POST) == 1 AND
(isset($_POST['submit']) OR
isset($_POST['firstname']) OR
isset($_POST['lastname']) OR
isset($_POST['address']) OR
isset($_POST['ZIP']) OR
isset($_POST['phonenumber']) OR
isset($_POST['mail']) OR
isset($_POST['group'])
))
Either way it's not a very elegant way of doing this - but it will work.
If you want only one value from a field which is set to required (if possible, use javascript, or HTML5 has a required attribute for that), simply ignore other values from other fields:
<?php
if ( isset( $_POST['submit'] ) ) {
$wanted_value = addslashes( strip_tags( $_POST['input_name'] ) );
// preventing from sql injection
// ignore other values
// and start manipulating it
}
?>
One suggestion would to be to use javascript and your onSubmit function on the form in addition to a serverside check. Using that, you can check all of your fields, and alert the user to fill some in BEFORE it gets submitted to the server.
In a javascript function check all of your inputs for a correct input, and allow the data to be sent to the server if it is all filled in correctly, or pop up an alert saying what else needs to be done before it can be submitted.
Doing this check strictly serverside will require a server request to check the input every time, as opposed to having the client check it, and submit it only if everything is correct.
Assuming you want to send the form if there's at least one field that's filled, you could use the following if-statement:
if(count($_POST) > 1)
This allows you to submit the form and have at least one field filled, but you can also have more fields filled.
If you want to send the form only if there's one field that's filled, you could change the above if-statement to the following:
if(count($_POST) == 2)
This allows you to have only one field filled.
The reason I use "== 2" is because the submit-button is also something that will be sent.
If you want to allow all the fields to be empty, you can use the following if-statement:
if(count($_POST) > 0)
This would allow you to submit the button and leave all the other fields empty.
The reason this works is because $_POST is a pre-defined array-variable.
To ensure that the user only uses fields that you want them to use and still keep the code clean, you can use an array.
Do the following:
$allowed_fields = array('firstname','lastname','address','ZIP','phonenumber','mail','group');
And then just add the following to your if-statement:
if(count($_POST) == 2 AND in_array($allowed_fields, $_POST))
Basically i have a form where a studentID is inputted, i then want to check id the inputted studentID is in the database, if it is post the form to the next page. If not then display an error on the page where you input studentID
Don't really know where to start
Cheers
is this what you want?
<form id = "form" action = "./?page=markandfeedback" method = "post">
<br>
Mark for:
<INPUT id="stud" onkeypress="return isNumberKey(event)" type="text" name="stud" value="Enter Student Number">
<input type="submit" value = 'Continue'>
<?
$studID = $_POST['stud'];
$module2 = $_SESSION['module'];
$ex = $_POST['exer'];
$studerr = array();
$sql = 'SELECT * FROM `student`, `modules` WHERE `studentID` = '.$studID.' AND `moduleCode` = '.$_SESSION['module'];
$result = mysql_query ($sql);
// echo $_SESSION['module'];
if ($result == NULL) { // nothing found
echo "the student id you entered is not in the database";
}
else {
$_SESSION['student'] = $studID;
Header("Location: http://www.whereever.com/"); // send the browser where you want
exit();
}
?>
EDIT:
I went over the other answers. I assume you check for mysql injection properly. I recommend implementing AJAX AFTER everything works and is secure. The idea behind my solution was to solve the problem as simple as possible. If you want to make something fancy out of it you could:
generate the whole form via php and tell the user in the input field, that the id wasn't found
tell your Javascript to present the information in some fancy way
Use AJAX. Everybody loves forms with AJAX.
You could, as suggested, assume that the user entered a valid id. You would check on the "whereever" page wether the id is actually valid. If it weren't, you would simply send the user back to the form and tell the php to output an error message (maybe via get). This possibility is not usual, I am not sure if it has any advantages.
the mysql_num_rows hint is nice, too, if you don't want any data from the user. I thought you wanted to do something with the data because of the SELECT *.
Make a seperate controller that does the checking of the username.
Use ajax to check if user input is valid or not.
So you'll have something like this:
<input id="stud" onchange="checkStudentId(this)" />
<script>
function checkStudentId(inputElement) {
var id = inputElement.value();
$.ajax({
url: "test.html",
context: {id:id}
}).done(function() {
// Check the return result
});
}
</script>
Here is a reference to jquery ajax
http://api.jquery.com/jQuery.ajax/
You actually have to connect to the server in some fashion to figure out of the student exists. What you'd normally do in this situation is submit the form to the server and do validation server-side. If the student exists, you return the "next" page. If the student doesn't exist, then you return (or redirect to using a Location header) the same form again with an error message.
Another popular method would be to use an AJAX request to check asynchronously (which I see many other people are recommending). I'd only recommend this way if you're actually doing validation right as they've finished entering the student id and are showing an error message in real-time, effectively. In this way, AJAX is a nice-to-have to provide quick user feedback, but not a real solution. Keep in mind that regardless of this, you need to check for and handle this when the form is submitted anyway, or at the least, consider what will happen when the form is submitted with an invalid id.
People can bypass this check (EVERY request from the client side is considered hostile, you can't implicitly trust anything)
Another user may have deleted the student ID between the time the check was done and the form was submitted
There could be an error in your code that causes validation to falsely pass or not to recognize a negative response
Doing AJAX onsubmit makes no sense, because effectively you're doubling the amount of work by making the server handle two separate requests in a row. It's simply the wrong answer to the problem.
The biggest trouble with this implementation is the PHP code can quickly get quite hairy and hard to follow as you have everything mixed together.
This is where you probably start to tip over using PHP like a templating language (mixed php code and html markup) and start getting into using a framework where your views (the HTML) are decoupled from your PHP code (if you're using the very-populate MVC pattern, this code is called your controller -- precisely because it controls how the server responds). This is how any professional developer will work. Kohana, CakePHP, and Zend are all examples of fairly popular MVC frameworks, all of which are used professionally.
You can do this in two different ways
AJAX - make ajax call to your server and check the ID if its exist display the error else go to the next page
PHP - put a hidden input in your form and make the action of the form to the same page and check everything their and keep the values of the input fields is the $_POST['field_name'];
And you can make the action into another page and return back variable or make a session to hold the error message
Try this:
<?
if(isset($_POST['stud'])){
$studID = $_POST['stud'];
$module2 = $_SESSION['module'];
$ex = $_POST['exer'];
$studerr = array();
$host="hostname";//your db host
$user="user";//your db user
$pass="pass";//your db pass
$conn=mysql_connect($host,$user,$pass);
$sql = 'SELECT * FROM `student`, `modules` WHERE `studentID` = '.$studID.' AND `moduleCode` = '.$_SESSION['module'];
$result = mysql_query ($sql,$conn);
if(mysql_num_rows($result)>0){//the id was found in the DB, do whatever here...
echo $_SESSION['module'];
$_SESSION['student'] = $studID;
Header("Location: http://www.whereever.com/");//redirect to wherever
$error=false;
}
else{//id was not found
$error=true;}
}//end of isset
?>
<? if($error===true){?> <div> The id was not found.... </div> <?}?>
<form id = "form" action = "<? echo $_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']; ?>" method = "post">
<br>
Mark for:
<INPUT id="stud" onkeypress="return isNumberKey(event)" type="text" name="stud" value="Enter Student Number">
<input type="submit" value = 'Continue'>
So what this does is: When the user hits submit, conects to the DB, and checks if the ID exists...if it does, then it redirects it to wherever.com (see comments) and if it don't an error messege will show up. Be sure to change the db variable values to your own ($host, $user, $pass).
wondering what the the best way to achieve something is.
To summarise, I have a form that I load by ajax which I use for to both update and insert new rows into a database. To determine whether it is an update or an insert I use the below code (updated forms use the mysql query to populate the form fields).
My code seems sloppy and not best practice. Are there any other suggestion on what would be the best way to do this?
<?
require_once("config.php");
$insert = false;
$update = false;
$targID = 0;
if(isset($_POST['targID'])){
$targID = $_POST['targID'];
$targRow = mysql_fetch_array(mysql_query("select * from events where eventid=$targID"));
$update = true;
}else{
$insert = true;
}
?>
<script type="text/javascript">
var insert = <? echo $insert; ?>+0;
var update = <? echo $update; ?>+0;
......javascript button events, validation etc based on inssert/update
</script>
You already know in the client whether it is an update or an insert, by the fact that you send or do not send the POST data item. So I would write JS in the original page to control the submit and what to do with the data that is sent back. It's difficult to write code without seeing the rest of the page, but at pseudo-code level, you could do the following:
use onsubmit() to catch original submit action
look to see if targID provided
if yes, send update request to server. When row data comes back, fill out form details and display form (you can 'show' a hidden DIV containing the form, for example)
if no - do you need to send anything? - just reveal an empty form (again, show a previously hidden DIV)
Hope this is useful in some way.
You should use native mySQL:
INSERT ... ON DUPLICATE KEY UPDATE
See:
http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
What's the point in determining that on the client side? Does it make any difference?
For the server side I'd use $targID passed from the hidden field. if it's greater than zero - update, otherwise - insert.
In Yahoo or Google and in many websites when you fill up a form and if your form has any errors it gets redirected to the same page.
Note that the data in the form remains as it is. I mean the data in the text fields remains the same.
I tried ‹form action="(same page here)" method="post or get"›. It gets redirected to the page, but the contents of the form gets cleared.
I want the data to be displayed.
You know how tiresome it will be for the user if he has to fill up the entire form once again if he just forgets to check the accept terms and conditions checkbox.
Need help!
You need to do this yourself. When the page gets posted you'll have access to all the form values the user entered via $POST['...']. You can then re-populate the form fields with this data.
Here is a modified version of what I use for very simple websites where I don't want/need an entire framework to get the job done.
function input($name, $options = array()) {
if(!isset($options['type'])) $options['type'] = 'text';
$options['name'] = $name;
if(isset($_POST[$name]) && $options['type'] != 'password') {
$options['value'] = htmlspecialchars($_POST[$name]);
}
$opts = array();
foreach($options as $key => $value) {
$opts[] = $key . '="' . $value . '"';
}
return '<input ' . implode(' ', $opts) . '/>';
}
(I have a few similar functions for <select> and <textarea> and so on)
When you're building fields you can do something like:
First Name: <?=input('first_name')?>
Last Name: <?=input('last_name')?>
Password: <?=input('password', array('type' => 'password'))?>
If you process your forms in the same page as the form itself, they will get auto filled if there are any errors. Most frameworks, though, do all of this for you (and in a much better way than the code above), I personally suggest CakePHP or CodeIgniter.
This is not done automatically. They get values from post / get and then assign the values the user typed to the template. What you see is html that was generated from the script that handled user values.
If you put your form and the form data processing in the same script, you can easily print out the data that has already been entered in the form, e.g.:
$valid = false;
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (isset($_POST['name']) && $_POST['name'] == 'Hugo') {
$valid = true;
} else {
echo '<p>Seriously, you have to enter "Hugo"!</p>';
}
// more data processing
if ($valid) {
echo '<p>Everything’s fine!</p>';
}
}
if (!$valid) {
echo '<form action="" method="post">';
echo '<p>Please enter "Hugo": <input type="text" name="name" value="', (isset($_POST['name']) ? htmlspecialchars($_POST['name']) : ''), '"></p>';
echo '<p><input type="submit"></p>';
echo '</form>';
}
Well this is not nice example but that’s how it works.
a lot of frameworks do this job for you, so dont waste your time doing this manually
You'll have to check the data within the same file, and if it is correct, then you redirect to the correct location. Then you can use the $_POST or $_GET information the user posted and he can fix the error(s).
You can use two approachs (they're not mutually exclusive):
Use JavaScript to help the user before he submits the form. That way, you save a roundtrip to the server.
What you asked for:
In the form, fill the value attributes of the fields with the data sent back from the server. For example: you send a field name, which you get as $_POST['name'] in PHP (assuming you used method='post'. If you send back the data and modify that field adding value='<?php $_POST['name']; ?> you should get your data back.
If you're using a template or framework system (I've incorporated the Smarty engine into several projects of mine), you can usually tweak the templates so they automatically fill fields with values if they detect that the $_POST[$variable] value corresponding to their field is set.
As for the passwords, as far as I understand it (I could be wrong): it's a convention that minimizes the amount of time that password is being sent over the wire, hence shrinking the window for anyone who may be sniffing to pick up on the text. It's just good practice to leave password fields blank, is all.