Form validation - php

I need to create a form that has many of the same fields, that have to be inserted into a database, but the problem I have is that if a user only fills in one or two of the rows, the form will still submit the blank data of the empty fields along with the one or two fields the user has filled in.
How can I check for the rows that have not been filled in and leave them out of the query?
or check for those that have been filled in and add them to the query. . .
The thank_you.php file will capture the $_POST variables and add them to the database.
<form method="post" action="thank_you.php">
Name: <input type="text" size="28" name="name1" />
E-mail: <input type="text" size="28" name="email1" />
<br />
Name: <input type="text" size="28" name="name2" />
E-mail: <input type="text" size="28" name="email2" />
<br />
Name: <input type="text" size="28" name="name3" />
E-mail: <input type="text" size="28" name="email3" />
<br />
Name: <input type="text" size="28" name="name4" />
E-mail: <input type="text" size="28" name="email4" />
<input type="image" src="images/btn_s.jpg" />
</form>
I am assuming that I could use javascript or jQuery to accomplish this, how would I go about doing this?
Thanx in advance for the help.

As others have said, it's bad practise to rely on javascript as your only form of validation. Look to javascript as a way to help your users submit valid data - but you should always validate on the server side. With that in mind, here's my suggestion:
<form method="post" action="thank_you.php">
Name: <input type="text" size="28" name="name1" />
E-mail: <input type="text" size="28" name="email1" />
<br />
Name: <input type="text" size="28" name="name2" />
E-mail: <input type="text" size="28" name="email2" />
<br />
Name: <input type="text" size="28" name="name3" />
E-mail: <input type="text" size="28" name="email3" />
<br />
Name: <input type="text" size="28" name="name4" />
E-mail: <input type="text" size="28" name="email4" />
<input type="image" src="images/btn_s.jpg" />
</form>
<?php
$num = 4; //Number of times the field is repeated
for($i = 1; $i <= $num; $i++){
if($_POST['name'.$i] != '' && $_POST['email'.$i] !=''){ //Only process if name and email are not blank
$thisname = $_POST['name'.$i];
$thisemail = $_POST['email'.$i];
//Your code here
}
}
?>

It's good to use javascript for form validation, but you shouldn't rely on it. The first thing to do is to check the values in $_POST in PHP, and make sure they're something valid looking (or at the very least, check that they're not "").
To check with javascript, you would put an onSubmit="..." in the form tag, which returns false if the form data is invalid (meaning "don't submit the form"). And you'd also probably want an alert, or you could modify the page somehow to indicate the problem. I'm not going to write out a form validation script for you though.

You can do JavaScript validation by using the submit button to call a JavaScript function instead of submitting the form. If the data passes your validation criteria, the JavaScript function can then submit the data. However, you should not rely completely on JavaScript validation. If the user has JavaScript disabled, their data will not be validated, so your PHP application must be robust enough to handle blank data. It isn't just blank data that you need to be concerned with, though. You need to validate the user input for garbage and sanitize the data before using it in the database.

I don't know the exact PHP syntax, but I'll write some pseudo-code that ought to do the trick. The basic idea is when you retrieve the $_POST values, you'll want to create a new hash that has values that are acceptable and then you can pass that hash to whatever methods needs to build out queries or whatever. The way I'll do this is to remove invalid values from the hash entirely, so it appears they were never there. Obviously, you can do this differently (mark them as invalid, etc).
$cleaned_args = array();
foreach ($_POST as $key => $value) {
if ($_POST[$key] != "" && is_valid_email($_POST[$key])) {
$cleaned_args[$key] = $_POST[$key];
}
make_db_call_or_whatever($cleaned_args);
where is_valid_email is a method that maybe PHP has or you have to write. You could even generalize the if clause into an is_valid($_POST[arg]) method if you want, but it depends on how complex the situation is.
Hopefully, this helps to give you an idea of how to do this. I think this will be easier than dynamically removing inputs with JavaScript before the form submission and, as mentioned, will be more secure than doing it only on the client side.

Related

How to pass php variable FORM data to mail handler?

I currently have a form built with HTML/PHP that has some variable data that I'm unable to pass to the mail handler. The inputs with the variable data are blank upon sending mail.
The HTML Form:
<form action="mail-handler.php" method="POST">
<label>First Name:</label>
<input name="T1" type="text" value="<?php print($_GET['firstname']); ?>" disabled="" />
/*Non variable data still needs to pass*/
<label>Phone*:</label>
<input name="phone" type="tel" required="" />
<input type="submit" value="Submit">
</form>
The PHP Mail Handler:
$firstname = $_POST['firstname'];
$phone = $_POST['phone'];
$msgBody="First Name: $firstname\n
Phone: $phone\n";
... and so on.
The form works for every input except the one with the variable data $firstname
How can I get the variable form value for "first name" to pass to the email handler?
So while #Martin and #Adder were correct with the incorrectly assigned var value, even after changing the mail-handler, the data would still not pass through the email.
I found the culprit to actually be the bit of HTML used to keep someone from editing the stored information. I had set the form fields with the variable data to be disabled="". Apparently this was the final block that was preventing the data transfer.
These are the changes I made to the code using the comment advice and changing the disabled status of the input.
<form action="mail-handler.php" method="POST">
<label>First Name:</label>
<input name="nameFirst" type="text" value="<?php print($_GET['firstname']); ?>" readonly="" />
/*Non variable data still needs to pass*/
<label>Phone*:</label>
<input name="phone" type="tel" required="" />
<input type="submit" value="Submit">
</form>
PHP did not like the disabled status so readonly="" got the job done there. Then I changed the var names to better suit my needs:
$nameFirst = $_POST['nameFirst'];
$phone = $_POST['phone'];
$msgBody="First Name: $nameFirst\n
Phone: $phone\n";
This worked very well. Don't use disabled="" on a form in which you want to pass variable data, it won't work. Use readonly="" instead.

How to create a form where input elements are already set but one must remain fixed?

I am feeding my forms preset data values from another file in a MVC application. One of the data set attributes, the ID, is to remain fixed and cannot be updated. Only the names, phones numbers etc can be updated. My issue is that I need to have something set with this that I can submit, just like the other preset data; however unlike the other preset data I cannot put this in a form as a user may change it.
<form action="crud.ctrl.php?act=update" method="post">
<label>ID: <?=$data1["id"]?> <br /><br>
<label>First Name:</label> <br><input type="text" name="fnameUP" id="fnameUP" value="<?= $data1["fname"] ?>"> <br />
<label>Last Name:</label> <br><input type="text" name="lnameUP" value="<?= $data1["lname"] ?>""> <br />
<label>Phone:</label> <br><input type="text" name="phoneUP" value="<?= $data1["phone"] ?>""> <br />
<label>Email:</label> <br><input type="text" name="emailUP" value="<?= $data1["email"] ?>""> <br />
<label>Location:</label> <br><input type="text" name="locationUP" value="<?= $data1["location"] ?>""> <br />
<label>MC:</label> <br><input type="text" name="mcUP" value="<?= $data1["mc"] ?>""> <br />
<label>Position:</label> <br><input type="text" name="posUP" value="<?= $data1["pos"] ?>""> <br />
<label>Department:</label> <br><input type="text" name="deptUP" value="<?= $data1["dept"] ?>""> <br />
<input type="submit">
</form>
one way to solve this issue would be to have another unique column in the original table. For example you could 'salt' the ID and hash that or use some other form of creating a long enough string to prevent the user to guess any of the existing "IDs".
And then just include that column in the form as a hidden input field for example
<input type="hidden" name="custom_id" value="<?=$data1["custom_id"]?>">
that way even if the user does mess with the ID, there is a very small chance for him to be able to change another record. The more complex your hashing, the smaller the chance.
If that is not secure enough, my next idea would be to have another column/table in the database where you generate a hash when retreiving the data that will be shown in the form and only allow updating the records that have that value set. that way the only "editable" rows are the ones where someone requested the edit form in the last X minutes.

HOW to add increment value to $_POST['variable'] in php?

I am using dynamic form where user add more input text boxes for a certain field he want and the name of each box change with an increment like:
<form method="post" action="somescript.php">
<input type="text" name="textbox" />
<input type="text" name="textbox1" />
<input type="text" name="textbox2" />
<input type="text" name="textbox3" />
.... and so on
</form>
I want to echo these data following a loop:
<?PHP
$k=$_POST['counter']; //counter value coming as post variable
for($i=1$i<=$k;$k++){
echo $_POST['textbox'.$i]; //something like this......?
}
?>
Please reply.
Use array notation instead.
<form method="post" action="somescript.php">
<input type="text" name="textbox[]" />
<input type="text" name="textbox[]" />
<input type="text" name="textbox[]" />
<input type="text" name="textbox][" />
.... and so on
</form>
When the form is submitted, $_POST['textbox'] will then be an array, and you can loop over it:
foreach ($_POST['textbox'] as $textbox) {
echo $textbox;
}
I just came across this issue because I had blocks of data that needed to be created dynamically and
echo $_POST["textbox$i"];
worked without the concatenation in it. Let me know if this is bad practice, it works in my situation though. The array way didn't work for me. Sorry for posting this on a 3 year old question. I'm not sure if that's bad practice. Thanks.

form data not getting passed

I'm practicing form validation with JavaScript but when I try to retrieve the data from the page it submits to I can't get it.
form.html
<body>
Hello.<br />
<form onsubmit="return validate()" action="process.php" method="POST">
Enter name: <input type="text" id="name" /><br />
Enter phone number: <input type="text" id="number" /><br />
Enter password: <input type="password" id="paswd" /><br />
Is there anything else you would like to add: <input type="text" id="anything" /><br />
<input type="submit" value="Check Form" />
</form>
</body>
process.php
<?php
echo 'Here: '.$_POST['number']
?>
Whatever index I use I get " Undefined index: line 2". What am I doing wrong?
EDIT: So I can't use the id attribute I need the name? Is there anyway to prevent coding redundancy since the value of all names will be the same as the corresponding id?
You need name attribute in your fields
<input type="text" id="number" name="number" />
$_POST looks for the name attribute in the field to capture the field values and not id
Your inputs need the name of the element.
Such as:
<input type="text" id="number" name="number" />
The Php gets the form data looking these names, not the ids.
you forgot name of input:
<input type="text" id="number" name="number" />
You need to give your form elements names.
<input type="password" id="paswd" name="paswd" />
Interestingly names and ids share the same namespace. If you don't really need the ids, leave them be. Inside a validate function you can always access all elements with the elements object of the form.
// called onsubmit
var validate = function(e) {
if (this.elements["paswd"].value.length < 4) {
alert("password needs to have at least 4 characters");
return false;
}
return true
};
I usually append the input type to my ids to differentiate them from field names
<label for="paswd-txt">Password: </label>
<input type="text" name="paswd" id="paswd-txt" />
<label for="save-cb">Remember me: </label>
<input type="checkbox" name="save" id="save-cb" value="1"/>
So like Vitor Braga said your inputs need the name of the element, but you only need this if you are using PHP to hadle the values of form in the submit, if you are using javascript to validaate like you said your were praticing you can obtain the value like this:
document.getElementById("number").value

Adding multiple inputs to file php form submit

I have a form that looks like so:
<label for="fullpath"><span class="required">*Full Path of folder to change access:</span></label>
<input name="fullpath" id="it10" type="text" size="50" maxlength="50" />
<br />
<small>Example: g:\A\Folder or j:\Your\Folder</small><br />
<div class="bgdiff">
<label for="userpermissiongroup">User Permission Group to be changed:</label>
<input name="userpermissiongroup" type="text" id="it11" size="50" maxlength="50" />
<small>If Known...</small></div>
<br />
<label for="addreadaccess">Additional users requiring read access:</label>
<input name="addreadaccess" type="text" id="it12" size="15" maxlength="15" />
<br />
<small>AD Username</small><br />
<div class="bgdiff">
<label for="addauthoraccess">Additional users requiring author access:</label>
<input name="addauthoraccess" type="text" id="it13" size="12" maxlength="12" />
<br />
<small>AD Username</small></div>
<br />
<label for="removeaccess">Users to be removed from access:</label>
<input name="removeaccess" type="text" id="it14" size="12" maxlength="12" />
<br />
<small>AD Username</small><br />
<div class="bgdiff">
<label for="supervisor"><span class="required">*Data Steward, Program Manager, Project Lead, or Supervisor who can authorize access changes:</span></label>
<input name="supervisor" type="text" id="it15" size="30" maxlength="30" />
<br />
<small>AD Username</small></div>
<br/>
<label for="phoneapprover"><span class="required">*Phone number of approving official: </span></label>
<input name="phoneapprover" type="text" id="it16" size="30" maxlength="30" />
<br />
<small>999-999-9999</small><br />
</fieldset>
</div>
I would like to give users the option to add all of this info to this form more than 1x before submitting. (say 10x max) I have run a couple ideas through my head. 1 is using Javascript to create the new fields and then parse them with my php script somehow. 2 is put say 10 code snips just like the form above in the code and hide them until the user clicks ADD ANOTHER.
Each input needs to be unique as I am submitting this info thought a simple $_REQUEST php script. I understand how to do this with 1 input and a for each loop, but am not sure how to make it work with such a large amount of inputs, labels, etc...
<?php
foreach($_POST['newdata'] as $value) {
echo "$value <br />";
}
?>
Anyone have some suggestions on the best way to go about this? I am not sure adding his form via JS is the best idea, so just displaying the new info from a hidden div seems quicker and easier...
If you append [] to your form field names, PHP will take those fields and turn them into an array, e.g.
<input type="text" name="field[]" value="first" />
<input type="text" name="field[]" value="second" />
<input type="text" name="field[]" value="third" />
would produce the following $_POST structure:
$_POST = array(
'field' => array(
0 => 'first',
1 => 'second',
2 => 'third',
)
);
The alternative is to append incrementing numbers to each field name, as you duplicate the existing field sets for each new block. This provides a nice separation between blocks and allows you guarantee that related fields have the same numerical tag, but it does complicate processing.
It's not so difficult: main idea is to use IDs for each iteration, so your inputs will have unique names and will be processed without problems
for ($i=0;$i<10;$i++){
echo "<input name='removeaccess' type='text' id='it14_{$i}' size='12' maxlength='12' />";
}
So, you take your code of current set of inputs with lables and add to input names IDs, formed on each circle iteration. Be carefull about ' and "!

Categories