How to validate form with PHP and HTML? - javascript

I am currently working on a project for a web development class I am taking in which I have to create a registration page for a marketing product and add user details to a database. I've got the basic code working but, after speaking with my teacher, I need to add some form of data validation to the website. I have tried marking the input fields as required in HTML5 as well as using a separate JavaScript Validator but nothing works, if I submit the form, my PHP script process without the data being validated.
My goal is for the data to validated directly on the form, so that error messages appear on the form itself versus on a separate page. I currently have a check in my PHP code to query the database for an already existing email and kill the script and echo an error but it does so on another page.
Below is the code I have so far with the JavaScript validator in place. I am still learning PHP and HTML so I'm lost as to what else I can try. Can anyone help?
HTML CODE
<!DOCTYPE HTML>
<html>
<head>
<title>Registration</title>
<script src="scripts/gen_validatorv4.js" type="text/javascript"></script>
</head>
<body>
<div id="register">
<fieldset style="width:30%"><legend>Registration Form</legend> <!-- Give the table a width of 30% and a title of Registration Form -->
<table border="0"> <!-- Add border to table -->
<tr>
<form method="POST" action="registration.php" id="register"> <!-- Use POST to submit form data to registration.php -->
<td>First Name</td><td> <input type="text" name="firstname" ></td> <!-- Input field for First Name -->
</tr>
<tr>
<td>Last Name</td><td> <input type="text" name="lastname" ></td> <!-- Input field for Last Name -->
</tr>
<tr>
<td>Address 1</td><td> <input type="text" name="address1" ></td> <!-- Input field for Address 1 -->
</tr>
<tr>
<td>Address 2</td><td> <input type="text" name="address2"></td> <!-- Input field for Address 2 -->
</tr>
<tr>
<td>City</td><td> <input type="text" name="city" ></td> <!-- Input field for City -->
</tr>
<tr>
<td>State</td><td> <input type="text" name="state" ></td> <!-- Input field for State -->
</tr>
<tr>
<td>Zip Code</td><td> <input type="text" name="zipcode" ></td> <!-- Input field for Zip Code -->
</tr>
<tr>
<td>Phone Number</td><td> <input type="text" name="phonenumber" ></td> <!-- Input field for Phone Number -->
</tr>
<tr>
<td>Email</td><td> <input type="text" name="email" ></td> <!-- Input field for Email -->
</tr>
<tr>
<td>Sign up to marketing emails?</td><td> <input type="radio" name="marketingaccept" value="yes"></td> <!-- Radio button to be checked if user wants to sign up for marketing emails -->
</tr>
<td><input id="button" type="submit" name="submit" value="Register"></td> <!-- Submit button -->
</form>
<script type="text/javascript">
var frmvalidator = new Validator("register");
frmvalidator.EnableOnPageErrorDisplay();
frmvalidator.EnableMsgsTogether();
frmvalidator.addValidation("firstname","req","Please provide your first name");
frmvalidator.addValidation("email","req","Please provide your email address");
frmvalidator.addValidation("email","email","Please provide a valid email address");
frmvalidator.addValidation("lastname","req","Please provide your last name");
frmvalidator.addValidation("address","req","Please provide your address");
</script>
</tr>
</table>
</fieldset>
</div>
</body>
</html>
PHP CODE
<?php
define('DB_HOST', 'localhost'); // Define database host
define('DB_NAME', 'andrewha_fhsuproject1'); // Define database name
define('DB_USER','*******'); // Define database username
define('DB_PASSWORD','********'); // Define database password
$con=mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die("Failed to connect to MySQL: " . mysql_error()); // Connect to host or present an error if connection fails
$db=mysql_select_db(DB_NAME,$con) or die("Failed to connect to MySQL: " . mysql_error()); // Connect to database or present an error if connection fails
function newregister() // Create function newregister()
{
$firstname = trim($_POST['firstname']); // Grab data from the first name field and trim excess white space
$lastname = trim($_POST['lastname']); // Grab data from the last name field and trim excess white space
$address1 = trim($_POST['address1']); // Grab data from the address1 name field and trim excess white space
$address2 = trim($_POST['address2']); // Grab data from the address2 name field and trim excess white space
$city = trim($_POST['city']); // Grab data from the city field and trim excess white space
$state = trim($_POST['state']); // Grab data from the state field and trim excess white space
$zipcode = trim($_POST['zipcode']); // Grab data from the zipcode field and trim excess white space
$phonenumber = trim($_POST['phonenumber']); // Grab data from the phonenumber field and trim excess white space
$email = trim($_POST['email']); // Grab data from the email field and trim excess white space
$marketingaccept = $_POST['marketingaccept']; // Check to see whether the marketingaccept radio button is checked
$sql="SELECT email FROM RegisteredUsers WHERE email='".$email."'"; // Look through existing emails to prevent duplication
$resul=mysql_query($sql); // Perform above query
$num = mysql_num_rows($resul); // Check above query to see if any rows match
if ($num !=0){ // If a match is found...
die("Sorry, you can only register once!."); // ...the script is killed and an error is presented.
} else // If no match is found, the script continues.
$query = "INSERT INTO RegisteredUsers (firstname,lastname,address1,address2,city,state,zipcode,phonenumber,email,marketingaccept) VALUES ('$firstname','$lastname','$address1','$address2','$city','$state','$zipcode','$phonenumber','$email','$marketingaccept')"; // Create variable to insert Grabbed data to database table and corresponding columns
$data = mysql_query ($query)or die(mysql_error()); // Run above query or kill the script if an error is presented
if($data) // Verify $data was run
{
header('Location: thankyou.html'); // Redirect to thankyou.html
exit(); // End script
}
}
if(isset($_POST['submit'])) // Check to see if submit button was hit...
{
newregister(); // ...and go to newregister()
}
?>

I don't know if you underestimate or misunderstand the results of validation so forgive me if I am long winded here.
Your validation on the client is exactly that - it will only validate certain conditions are met on the client. Once the data is sent to the server, without validation/sanitization, you risk someone tampering and thrashing your database, or worse.
It would be possible for example to skip your client validation entirely and just enter an address in the address bar or via a script that would pretend to be a web browser sending data to your server.
The way your code is written above, the server will receive data and it can be engineered (rather easily) via a single input box to delete all the data in your database, or pending the server configuration, possible to destroy your server.
An article elsewhere on stackoverflow should help discuss this subject in greater detail. I just did a quick search and found this one: What's the best method for sanitizing user input with PHP? Read some of the answers.
Now... with regards to validating your form data, I recommend you use jquery. It is a javascript add on library (meaning its entirely written in javascript) but it is cross browser compatible (there are variations in how javascript in some browsers handles data so your plain javascript might or might not work on all browsers. However code written in jquery will work in all browsers).
The simplicity of validating your form data could be done by adding a
class="required"
in to each input tag in your form.
Then, with jquery, you could perform something like the following
// e will contain input field names of input tags that require but are missing data
var e=new Array();
// Get all input boxes with class "required", check the data input
// if the input length is less than one character in length, it
// will add the id tag to the "e" array.
$("input.required").each(function(){
if( $(this).val().length<1 )
{
e.push( $(this).prop("id") );
}
});
// If e array has more than zero elements, it means more than zero input
// input tags are missing data and thus an alert is shown
if( e.length>0 )
{
alert( "The following data fields are missing data:\n"+e.join(", ") );
}

Related

How to autopopulate a text box in html and php

So I have a page where a new user can input a username pswrd ect. then they fill out some information. An admin can then go and see whos registered and If so desired can go and edit the information entered by the user. What happens is when the admin clicks a button that redirects them to the schedule page I want the text fields to already be populated with all the information. I have confirmed with echo statements that I do have all the correct information at button press, I just cant get the text fields to update when the page loads.
Here is an example of one of the text boxes
<input type="text" id = "textBoxSchedule" name="email" placeholder="Email" value="<?php echo $email?>" required>
I have correctly set the value of $email, but what my guess is, is that HTML runs, creates the text box and then the PHP runs so its set after the value is created.
Thank you for your help!
EDIT:
Ok so heres how I get the information. From the admin page, I know what user I want to edit. So I pass that user name value through the $_SESSION variable and then I can use that one piece of information to get the rest of the text fields. Im not sure if this will have an affect or if its something I can utalize but the text boxes are below a header of:
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>" method = "post">
(im partner coding this and he wrote a majority of this so im still working on understanding it all.)
Try using javascript for it.
<input type="text" id = "textBoxSchedule" name="email" placeholder="Email" required>
<?php echo "<script>myFunction(".$email."); </script>" ?>
The JS is ~
myFunction(x){
document.getElementById('textBoxSchedule').value = x;
}
Don't have enough reputation to comment, so I'll post an answer
<?php echo $email?>
You forgot the semicolon ( ; ) and you didn't leave a space before ?>
Also although it's not false, you should not put spaces before and after = symbol in html attributes
id = "textBoxSchedule"
Lastly I presume you reload the page and you don't expect php to run in client's browser?
I’ve tested your script on a blank php page with the following code:
<?php
$email = "test#email.com";
?>
<input type="text" id = "textBoxSchedule" name="email" placeholder="Email" value="<?php echo $email?>" required>
And I’ve managed to get the text box showing properly.
If you still have a problem showing your text box, you might want to double check the value of your $email variable of the code prior and after the example you’ve given us.

How to generate a link for every row/record found in a database to use as a way to populate a form when clicked on?

I have a website with members and when members are logged in they have access to a page with a form that they can use to submit information. This form has a hidden input “user_email” with a pre loaded defualt value that is equal to the logged in members email address on file.
<form action="xxx.php" class="well" id="xxx" name"xxx" method="post">
<input type="hidden" id="user_email" name="user_email" value="xxx#email.com">
<input type="text" id="invoice_id" name="invoice_id">
<input type="text" id="other1" name="other1">
<input type="submit" value="Submit">
</form>
I need a script that will take that pre filled value of a forms input named “user_email” and search and fetch every row/record of data in my database that have that same value under the “user_email” column.
Then For every row/record matched/found I'm trying to have a link generated
When any generated link is clicked, It needs a function to pre fill the form with its corresponding fetched row/record data.
I cant imagine how much time it would take for one to posses the skills required to compose the code it takes to achieve the above...Any point of direction or any help is greatly appreciated...thanks for your time.
You could make a request to a PHP script that reads the email, finds the and returns associated data as an array of objects, and outputs the HTML links, with each link containing the data in custom 'data-x' attributes. For example:
//email_details.php
<?php
//your function that returns an array of objects
$rows = find_the_data($_GET['user_email']);
foreach($rows as $row) { ?>
<a class="email_data_link" href="#" data-invoice-id="<?php echo $row->invoice_id ?>" data-other1="<?php echo $row->other1 ?>">A link</a>
<?php } ?>
You could then use a tool like jquery to modify the form when a link is clicked
$('.email_data_link').on('click', function() {
//copy the data embedded in the clicked link to the form
$('#invoice_id').val($(this).data('invoice-id'));
$('#other1').val($(this).data('other1');
});
Without additional context and understanding your level of expertise, it's hard to create a truly helpful example, but this may at least give you some food for thought.
Best of luck

How to create a user generated list of links for different records/rows in a database that populate an html form when clicked?

Hi I have this html form. This form is used to collect and store user/members submitted information. It uses a database with several columns 2 of importance "user_email" & "invoice_id". In the form the "user_email" input is hidden and upon page load is equal to the the value of a logged in users provided email address on file. When a user submits multiple form submissions, multiple records with the same user_email are created in the database. So say for instance if user1 submitted 3 forms there would be 3 records/rows in my database all with their "user_email" column with the same email.
I'm trying to figure out how to create a user generated list of links that will populate a form using data fetched from a database when clicked on.
Here's the best way I can explain what scenario I'm trying to make possible...
1)Search & fetch the data for every record/row in a database table where the "user_email" column value matches the value of a sample_form1 input name: "user_email".
<form action="xxx.php" id="sample_form1" name"sample_form1" method="post">
<input type="hidden" id="user_email" name="user_email" value="xxx#email.com">
<input type="text" id="invoice_id" name="invoice_id">
<input type="text" id="other1" name="other1">
<input type="text" id="other2" name="other2">
<input type="submit" value="Submit">
</form>
2)Generate a list of links for each found record each one link corresponding to a different record/row found, using the value of the "invoice_id" column as the generated link's label/text.
EXAMPLE:
Click here to view InvoiceID#001
Click here to view InvoiceID#002
Click here to view InvoiceID#003
3)Populate sample_form1 with the fetched data when a generated link is clicked.
Thanks for your time and help in advance.
1)Search & fetch the data for every record/row in a database table where the "user_email" column value matches the value of a sample_form1 input name: "user_email".
$command = "SELECT invoice_id, user_email FROM tableName WHERE user_email = '$user_email'";
2)Generate a list of links for each found record each one link corresponding to a different record/row found, using the value of the "invoice_id" column as the generated link's label/text.
I didn't quite get you but
while ($row = mysql_fetch_assoc($result)
{
echo 'Click here to see InvoiceID #' . $row['invoice_id'] . '';
}
3)Populate sample_form1 with the fetched data when a generated link is clicked.
What do you want? Just get the data from the POST request?
<?php // xxx.php
// if form is submitted through the POST
if (strtoupper($_SERVER['REQUEST_METHOD']) == "POST")
{
// Get required fields
$user_email;
$invoice_id;
$other1;
$other2;
if (isset($_POST['user_email']) && $_POST['user_email'] != "")
$user_email = htmlspecialchars($_POST['user_email']);
if (isset($_POST['invoice_id']) && $_POST['invoice_id'] != "")
$invoice_id = htmlspecialchars($_POST['invoice_id']);
// Do same with $other1 and $other2
// Now you have to open a connection with DB and put the data
}
?>

Setting input value with javascript nullifies PHP post

I a have PHP form where I collect a bunch of values from text inputs, but for one input I have the input filled in via javascript (user selects a date from a calendar, that date then populates a text input). I've setup a simplified version of this:
<?php
$displayForm = true;
if ($_POST['submitFlag'] == 1) {
// Form was submitted. Check for errors and submit.
$displayForm = false;
$installationTime = $_POST['installation-time'];
// send e-mail notification
$recipients = "test#test.com";
$subject = "Test Email - Test Form Submission";
$message = wordwrap('Someone has filled out the secure form on test.com. Here\'s what they had to say:
Installation Time: ' . $installationTime .'
');
$headers = "From: test#test.com";
mail($recipients, $subject, $message, $headers);
// Output thank you message
?>
<h2>Thank You!</h2>
<?php if($installationTime == NULL){echo 'test failed: value submitted was null.';}else{echo 'test passed: value submitted was not null.';} ?>
<p>Your form has been submitted. Thank you for your interest in test.com.</p>
<?php
}
if ($displayForm) {
// If form was not submitted or errors detected, display form.
?>
<div class="note"><span class="required">*</span> Click me to set value of input.</div>
<form name="contactForm" id="contactForm" method="post" enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF']; ?>?state=submit">
<label for="installation-time" class="service-time">The time you have selected for installation is: <span class="required">*</span></label>
<input type="text" name="installation-time" id="installation-time" disabled value="<?php echo $_POST['installation-time']; ?>" />
<input type="hidden" name="submitFlag" id="submitFlag" value="1" />
<input type="submit" name="submit" id="submit" value="Sign-Up" />
</form>
<?php
} // End of block displaying form if needed.
?>
And then in jQuery I do one of these:
$('.note').click(function(){
$('#installation-time').val('test string');
});
When I submit the form, the PHP variable that's supposed to collect that value is null. Every other input in the form works, and if I remove the javascript and manually enter the exact same text that I had set with JavaScript into the input it works as well.
The question really is why populating a field with javascript as opposed to manually typing the exact same string into a text input would break things. Again there are no errors and the input is populated correctly on the front end. Somehow posting the form just doesn't pick up on the value when it's set by javascript vs. typed manually. There has to be something really fundamental I'm missing here.
Any idea what's going on here? I've spent hours puzzling over this to no avail.
Update:
Code updated, test page:
http://dev.rocdesign.info/test/
Solution: can't post a disabled input. I actually tested that back in the beginning and must have missed that removing the "disabled" on the input made it work, so I mistakenly ruled it out and moved on.
Thanks for the responses everyone. And for anyone else with this problem: use a hidden input to post the value.

javascript and php do not work together

I'm writing the register page for my website.Here is my register page.Can anyone show me why it does not check whether The username is already in use or not.I don't know whether PHP and javascript can work together or not.
The html page is as follows:
<html>
<head>
<title>Register</title>
</head>
<body>
<script language="javascript">
function checkInput()
{
if(document.register.username.value=="")
{
alert("Fill in username");
document.register.username.focus();
return false;
}else if(document.register.password.value==""){
alert("Fill in your password");
document.register.password.focus();
return false;
}else {
<?php
if(isset($_POST['submit'])){
include "connect.php";
$username=$_POST['username'];
$query="SELECT username FROM user";
$result=mysql_query($query);
while($row=mysql_fetch_array($result)){
$arr[]=$row['username'];
}
if(in_array($username,$arr)){
?>
alert("Username is already in use");// this part does not work!
document.register.username.focus();
return false;
<?php
}
}
?>
}
}
</script>
<form name="register" method="post" action="dangki.php" onsubmit="return checkInput();">
<table width="289" height="185" border="1">
<tr>
<td colspan="2">register</td>
</tr>
<tr>
<td width="83">Username</td>
<td width="190"><input type="text" name="username" id="textfield" ></td>
</tr>
<tr>
<td>Password</td>
<td><input type="text" name="password" id="textfield2"></td>
</tr>
<tr>
<td>Re-type Password</td>
<td><input type="text" name="repassword" id="textfield3"></td>
</tr>
<tr>
<td colspan="2"><input type="submit" name="submit" id="button" value="Submit"> </td>
</tr>
</table>
</form>
</body>
</html>
Not, Javascript and PHP do not "work together" in that way. Javascript runs in your browser, PHP runs on the server before that. Therefore, you cannot use PHP for client side validation, only server side. For a first demonstration of this, just "view source" on what your page looks like to the browser.
You have to think of them separately. You have to have PHP just check what the form submits, and return a new page that indicates whether it was a valid/new username and allows the user to try again if needed.
You can sort of fake it with ajax, but even that is just sending a request to the server, which is run separately, and returns a result to the page, to be processed by a different function. It would get more complicated that your attempt.
PHP is evaluated on the server side. JavaScript is evaluated on the client side. That is to say: when a user makes a request to the server, the php is evaluated on the server, the resulting output is sent to the user, if there is javascript involved, it is evaluated on the client, after the php has evaluated.
This means that PHP can give messages to javascript, but javascript cannot send messages to php. In your code it looks like you want php to evaluate the user input that javascript is taking. This cannot be done because when the javascript is running, the php is already finished.
One way you could provide the functionality you want is to write php code to write the code for an array in javascript, containing all usernames. The javascript could then look through this array to tell the user if the username is taken. This has some flaws though, if you have a lot of users, you will be transmitting a lot of text to a new user. This may be a security problem too because everyone would be able to know all the user names of all the people registered with the site, there is also the potential for someone to load the page, type in their user name, wait a long time, have someone else create an account with their same name, and then the first person come back, submit the page, and then you will have two users with the same user name.
It may be easier, but less fun, to write the whole site in php first, and after it's all working, add the javascript to spruce up functionality.

Categories

Resources