My form Verification and Validation with php is not working - php

I have to verify and validate information inputted in an HTML form against a database created in phpMyAdmin. Currently, when I input my data and hit submit, I get a message that I have at the end of my PHP file. (Account not found). Also whatever transaction they select should be redirected to that page.
Is it giving me an error msg because I have the wrong name somewhere or is it skipping over all the functions?
This is the Form
<body>
<form name="form" action="Verify.php" method="post">
<h1>Lushest Lawns and Landscaping</h1>
<label for="input"><b>Landscaper's First Name: </b></label>
<input type="text" name="fname" placeholder="Example: John" required>
<label for="required"><b>REQUIRED</b></label>
<br>
<label for="input"><b>Landscaper's Last Name: </b></label>
<input type="text" name="lname" placeholder="Example: Doe" required>
<label for="required"><b>REQUIRED</b></label>
<br>
<label for="input"><b>Landscaper's Password: </b></label>
<input type="password" name="pass" placeholder="Example: Ba9877bb$Bb9" required >
<label for="required"><b>REQUIRED</b></label>
<br>
<label for="input"><b>Landscaper's ID#: </b></label>
<input type="number" name="id" placeholder="Example: 123456" required>
<label for="required"><b>REQUIRED</b></label>
<br>
<label for="input"><b>Landscaper's Phone#: </b></label>
<input type="number" name="Pid" placeholder="Example: 1234567890" required>
<label for="required"><b>REQUIRED</b></label>
<br>
<label for="input"><b>Landscaper's Email: </b></label>
<input type="text" name="email" placeholder="Example: abc#abc.com">
<br>
<label for="input"><br><b>Select a Transaction: </b></label>
<select id="transaction" name="transaction" required>
<option name="1">Search A Landscaper's Accounts</option>
<option name="2">Book A Customer's Appoinment</option>
<option name="3">Place A Customer's Order</option>
<option name="4">Update A Customer's Order</option>
<option name="5">Cancel A Customer's Appoinment</option>
<option name="6">Cancel A Customer's Order</option>
<option name="7">Create A New Customer Account</option>
</select>
<br>
<input type="checkbox" id="confirmation" name="emailconfirm">
<label for="checkbox"><b>Email the Transaction Confirmation</b></label>
<button class="button button5" name="submit">Submit</button>
</form>
</body>
This is the PHP file. I just removed the server name and everything for now but I have it in my file.
<?php
if(isset($_POST["submit"])){
session_start();
$servername = "";
$username = "";
$password = "";
$dbname = "";
$connection = mysqli_connect($server,$username,$password,$dbname);
if($connection-> connect_error){
die("Connection failed: " . $connection-> connect_error);
}
//Form input data
$Fname = $_POST["fname"];
$Lname = $_POST["lname"];
$Lid = $_POST["id"];
$Lpass = $_POST["pass"];
$transaction = $_POST["transaction"];
$Lemail = $_POST["email"];
$Lphone = $_POST["Pid"];
$_SESSION['id'] = $Lid;
$validate = true;
$verify = false;
function validate() {
//validate first name
if (empty($_POST["fname"])) {
echo ("First Name is required <br>");
$validate = false;
header( "refresh:3;url=Pro4.html" );
}
//validate last name
if (empty($_POST["lname"])) {
echo ("Last Name is required <br>");
$validate = false;
header( "refresh:3;url=Pro4.html" );
}
//validate id
if (empty($_POST["id"])) {
echo("Invalid ID: Enter 6-digit number <br>");
$validate = false;
header( "refresh:3;url=Pro4.html" );
}
//validate password
if (empty($_POST["pass"])) {
echo("Invalid Password: Enter 6-digit number <br>");
$validate = false;
header( "refresh:3;url=Pro4.html" );
}
//Validate transaction
if (empty($_POST["transaction"])) {
echo ("Please select a Transaction <br>");
$validate = false;
header( "refresh:3;url=Pro4.html" );
}
//Validate phone number
if (empty($_POST["Pid"])) {
echo("Invalid Phone Number <br>");
$validate = false;
header( "refresh:3;url=Pro4.html" );
}
//validate email
if(isset($_POST["emailconfirmation"]) && !empty($_POST["emailconfirmation"])) {
if(empty($_POST["emailconfirmation"])) {
echo("Please enter an Email <br>");
$validate = false;
header( "refresh:3;url=Pro4.html" );
} else {
$email = $_POST["emailconfirmation"];
if (!filter_var($email, 'FILTER_VALIDATE_EMAIL')) {
echo ("Invalid Email Format, Correct Format: email#example.com <br>");
$validate = false;
header( "refresh:3;url=Pro4.html" );
}
}
}
}
function verify($connection) {
$sql = "SELECT * FROM `Landscaper DB`";
$result = $connection -> query($sql);
while ($row = $result-> fetch_assoc()) {
if (($_POST["fname"]) == ($row["LFirstName"])) {
if (($_POST["lname"]) == ($row["LLastName"])) {
if ($_POST["id"] == $row["LID"]) {
if ($_POST["Pid"] == $row["LPhone"]) {
if ($_POST["pass"] == $row["LPassword"]){
return true;
}
}
}
}
}
}
return false;
}
validate();
if(validate()) {
$verify = verify($connection);
}
if($verify) {
//transaction
if($transaction == "1") {
header("Location: Landscaper.php" );
}
elseif($transaction == "2") {
header("Location: AppoinmentForm.html" );
}
elseif($transaction == "3") {
header("Location: OrderForm.html");
}
elseif($transaction == "4"){
header("Location: UpDateOrder.html" );
}
elseif($transaction == "7"){
header("Location: CreateAccount.html" );
}
elseif($transaction == "5"){
header("Location: CancelCusApoin.html" );
}
elseif($transaction == "6"){
header("Location: CancelOrder.html" );
}
}
else {
echo "Sorry, account not found.\n Please try again with a valid Name, ID, and Password.";
header( "refresh:3;url=Pro4.html" );
}
$connection -> close();
}
?>
DATABASE
This is the table of inputs that should work.

You're not going to pass validation because your select element options have no values, so transaction will be blank.
You have lots of badly formed html. Read up on forms, labels, input elements, and IDs, names, and values. Once you have the html ironed out then the server side validation will follow.

validate();
if(validate()) {
$verify = verify($connection);
}
For whatever reason you are calling the validate() function twice. You only need to call it once. Additionally, you are checking the return value of the validate() function with an if() statement, but your validate() function does not have any return statement. This means that the "return value" of this function is always NULL. This will result in the following code/execution:
validate();
if(NULL) {
$verify = verify($connection);
}
That way the if() block is never executed. So your verify() function is never called and your $verify variable is never updated, it stays false. When you want to use your verify() function in an if() statement, your function has to use the return statement to return a "result" like return true; or return false;.
Your $_POST['transaction'] field does not contain the name="..." values but instead the label content of the <option> entry. The syntax to set a (different) value for an <option> entry is set the value="..." attribute, something like:
<option value="4">Update A Customer's Order</option>
You can always check with var_dump($_POST); to see what the actual values are the browser is sending to your PHP script.

Related

Producing error messages in php validation

I am trying to validate a form using php, the code i have doesn't prevent the form from being submitted when the inputs are invalid, however, the error messages that i would like them displayed do not show on the form, the form is returned empty of error messages even tho i have them echo'ed inside the form. could you help me display the error messages upon unsuccessful submission of the form ? i added my form code and the php code. both are seperate files , the action in the form leads to the php validation code like so (action = "report_form_php.php).
<form method="post" onsubmit=" return formSubmit()" action="report_form_php.php">
<div class="error1" id= "errorMsg">* Required Fields</div>
<div class="error" id= "errorMsg1">*<?php echo $staffErr; ?></div>
<div>
<label for="staff_name"><b>Staff Name:</b></label>
<input class="field" id="staff_name" name="staffname" onclick=" return staffValidation()" onchange=" return staffValidation()" id="subject" type="text" placeholder="Staff Name" >
</div><br>
<div class="error" id= "errorMsg2">*<?php echo $emailErr; ?></div>
<div>
<label for="email"><b>Email:</b></label>
<input class="field" id="email1" name="email" onclick=" return emailValidation()" onchange=" return emailValidation()" type="email" placeholder="staff#wearview.com" >
</div><br>
<div class="error" id= "errorMsg3">*<?php echo $subjectErr; ?></div>
<div>
<label for="subject"><b>Subject:</b></label>
<input class="field" name="subject" id="subject1" onclick=" return subjectValidation()" onchange=" return subjectValidation()" type="text" placeholder="Subject Title" >
</div><br>
<div class="error" id= "errorMsg4">*<?php echo $problemErr; ?></div>
<div>
<select onclick=" return problemValidation()" onchange=" return problemValidation()" class="field4" name="problem_type" id="problemtypes">
<option value="">Problem Type</option>
<option value="Hardware">Hardware</option>
<option value="Software">Software</option>
<option value="Software&Hardware">Software & Hardware</option>
<option value="Other">Other</option>
</select>
</div><br>
<div class="error" id= "errorMsg5">*<?php echo $descriptionErr; ?></div>
<div>
<textarea class="field2" id="description1" name="description" onclick=" return descriptionValidation()" onchange=" return descriptionValidation()" placeholder="Description goes here" rows="15" cols="90"></textarea>
</div>
<div>
<button class="field3" type="submit" class="btn">Submit</button>
<input type="checkbox" id="notify" name="notify" value="">
<label for="notify">Inform me by email when issue is resolved.</label>
</div>
</form>
<?php
// define variables and set to empty values
$staffErr = $emailErr = $subjectErr = $problemErr = $descriptionErr= "";
$staffname = $email = $subject = $problem_type = $description = "";
// staff name validation:
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["staffname"])) {
$staffErr = "Staff Name is required";
} else {
$staff_name = test_input($_POST["staffname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z-' ]*$/",$staffname)) {
$staffErr = "Only letters and white space allowed";
}
}
// email validation:
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Please enter a valid email.";
}
}
// subject validation:
if (empty($_POST["subject"])) {
$subjectErr = "Subject is required";
} else {
$subject = test_input($_POST["subject"]);
// check if subject only contains letters and whitespace
if (!preg_match("/^[a-zA-Z-' ]*$/",$subject)) {
$subjectErr = "Only letters and white space allowed";
}
}
// problem type validation:
if (empty($_POST["problem_type"])) {
$problemErr = "Problem type is required";
} else {
$problem_type = test_input($_POST["problem_type"]);
}
// description validation:
if (empty($_POST["description"])) {
$descriptionErr = "A Description is required";
} else {
$description = test_input($_POST["description"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if ($staffErr == "" && $emailErr == "" &&$subjectErr == "" &&$problemErr == "" &&$descriptionErr == "") {
header("Location: insert_logs.php");
exit();
} else {
header("Location: log-it-reportsbeta.php");
exit();
}
?>
This basic php codes below should give you the ideas for 3 states of a form submission process to adjust your code properly.
success
system failure (bug or a temp. server issue for example)
invalid user data input
// data were valid && script's aim is achieved
if (isset($_SESSION['state']) && $_SESSION['state'] == 1) {
// your thanks/result page's content here;
echo 'Thanks. Transaction was successful.';
unset($_SESSION['state']);
return; // not to continue
}
// form not submitted yet
if ( false === (isset($_POST['submit']) && $_POST['submit'] = "your val")) {
require 'form.php';
return; // not to continue
}
// form submitted
require 'validate.php'; // PHP codes to validate data from POST global var.
// data are valid
if (valid($_POST)) {
// try what you aim with valid data
require 'perform_aim.php';
if (perform_aim_successful()) { // for example: record was inserted
$_SESSION['state'] = 1; // success state
header("Location: YOUR URL", TRUE, 301); // prevents reprocessing by F5 ($_POST is empty again by 301.)
exit; // exit after a redirect
}
else {
echo 'Your data was OK but script was failed. Try again later';
}
}
// invalid data
else {
print_r($err_msgs); // error messages from/by 'validate.php'
require 'form.php';
}

Submit functionality using php to prevent submission upon invalid inputs

I would like to validate a form on the server before submitting it to a database, i managed to write a php code that shows error messages for invalid inputs once the user clicks submit in the form, which is step one, however, step two is to prevent the form from submitting which is what i would like to know how , because despite error messages showing that input was invalid, the input goes to the data base. i tried to define a "$valid = true" variable , and then return it as false after each error message, but it didnt help ..
<?php
// define variables and set to empty values
$staffErr = $emailErr = $subjectErr = $problemErr = $descriptionErr= "";
$staffname = $email = $subject = $problem_type = $description = "";
$valid = true;
// staff name validation:
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["staffname"])) {
$staffErr = "Staff Name is required";
$valid = false;
} else {
$staff_name = test_input($_POST["staffname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z-' ]*$/",$staffname)) {
$staffErr = "Only letters and white space allowed";
$valid = false;
}
}
// email validation:
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Please enter a valid email.";
}
}
// subject validation:
if (empty($_POST["subject"])) {
$subjectErr = "Subject is required";
} else {
$subject = test_input($_POST["subject"]);
// check if subject only contains letters and whitespace
if (!preg_match("/^[a-zA-Z-' ]*$/",$subject)) {
$nameErr = "Only letters and white space allowed";
}
}
// problem type validation:
if (empty($_POST["problem_type"])) {
$problemErr = "Problem type is required";
} else {
$problem_type = test_input($_POST["problem_type"]);
}
// description validation:
if (empty($_POST["description"])) {
$descriptionErr = "A Description is required";
} else {
$description = test_input($_POST["description"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form method="post" onsubmit=" return formSubmit()" action="#">
<div class="error1" id= "errorMsg">* Required Fields</div>
<div class="error" id= "errorMsg1">*<?php echo $staffErr; ?></div>
<div>
<label for="staff_name"><b>Staff Name:</b></label>
<input class="field" id="staff_name" name="staffname" onclick=" return staffValidation()" onchange=" return staffValidation()" id="subject" type="text" placeholder="Staff Name" >
</div><br>
<div class="error" id= "errorMsg2">*<?php echo $emailErr; ?></div>
<div>
<label for="email"><b>Email:</b></label>
<input class="field" id="email1" name="email" onclick=" return emailValidation()" onchange=" return emailValidation()" type="email" placeholder="staff#wearview.com" >
</div><br>
<div class="error" id= "errorMsg3">*<?php echo $subjectErr; ?></div>
<div>
<label for="subject"><b>Subject:</b></label>
<input class="field" name="subject" id="subject1" onclick=" return subjectValidation()" onchange=" return subjectValidation()" type="text" placeholder="Subject Title" >
</div><br>
<div class="error" id= "errorMsg4">*<?php echo $problemErr; ?></div>
<div>
<select onclick=" return problemValidation()" onchange=" return problemValidation()" class="field4" name="problem_type" id="problemtypes">
<option value="">Problem Type</option>
<option value="Hardware">Hardware</option>
<option value="Software">Software</option>
<option value="Software&Hardware">Software & Hardware</option>
<option value="Other">Other</option>
</select>
</div><br>
<div class="error" id= "errorMsg5">*<?php echo $descriptionErr; ?></div>
<div>
<textarea class="field2" id="description1" name="description" onclick=" return descriptionValidation()" onchange=" return descriptionValidation()" placeholder="Description goes here" rows="15" cols="90"></textarea>
</div>
<div>
<button class="field3" type="submit" class="btn">Submit</button>
<input type="checkbox" id="notify" name="notify" value="">
<label for="notify">Inform me by email when issue is resolved.</label>
</div>
</form>
Here's an example (all PHP) without Javascript but with better security & email check. Tested on a working server. If you want an example with a properly protected insert statement, let me know and I'll add to this answer.
<?php
$name = $response_name = $email = $response_email = ""; // Clear variables
// Name (trims white space and doesn't accept names under 2 characters or over 20 characters)
if (isset($_POST['myform'])) {
$name = mysqli_real_escape_string($con, $_POST['name']);
if (empty($name) || strlen(trim($name)) < 2 || strlen(trim($name)) > 20) {
$response_name = "bad name";
}
// Email (checks for correct email format and tests a response from the email domain server example: gmail.com)
$email = mysqli_real_escape_string($con, $_POST['email']);
$email_host = strtolower(substr(strrchr($email, "#"), 1));
$email_host = idn_to_ascii($email_host.'.');
if (filter_var($email, FILTER_VALIDATE_EMAIL) === false || !checkdnsrr($email_host, "MX")) {
$response_email = "bad email";
}
if ($response_name=="" && $response_email=="") {
echo "data ok, proceed";
// Now send to MySQL table...
}
}
echo "
<form method='post'>
<label for='name'><b>Name:</b> $response_name</label>
<input name='name' type='text' value='$name' placeholder='Enter your name'>
<label for='email'><b>Email:</b> $response_email</label>
<input name='email' type='email' value='$email' placeholder='Enter your email' >
<button type='submit' name='myform'>SUBMIT</button>
</form>
";
?>
Note: For forms, Javascript is good for initial data error detection but to be really secure you would want to check with PHP and so if you're already using Javascript for forms you should be using AJAX as it's much more user friendly (no page reloading required) and you'll be able to reference an external PHP file which keeps code neater and tidier, at least IMO!

php If worth of html form is operated

I am making the login page in php.
However, no If worth of blank check of html form is operated (line4)
After entering in the html of the form, even if you press the login does not have moved if statement.
Since the cause is not know, I want you to tell me
if (isset($_POST["login"])) {//PUSH login button
//form blank check
if ($_POST["email"] = '') {
$error['email'] = "blank";
} else if ($_POST["pass"] = '') {
$error['pass'] = "blank";
}
}
if(!empty($_POST['email'])){
//email & password verification
if($_POST['email'] != '' && $_POST['pass'] != ''){
$email = $_POST['email'];
$pass = SHA1($_POST['pass']);
$query = "select * from human";
$result = mysqli_query($dbc,$query);
$data = mysqli_fetch_array($result);
if($data['email'] == $email) { //form email & password
if($data['pass'] === $pass) {
setcookie('email', $email, time()+(60*60*24*3));
setcookie('pass', $pass, time()+(60*60*24*3));
setcookie('name', $date['name'], time()+(60*60*24*3));
exit();
}else{
$error['match'] = "anmatch"; //Mismatch Error
}
}
}
<!DOCTYPE html>
<form action="" method="post">
<dl>
<dt>email</dt>
<dd>
<input type="text" name="email" size="35" maxlength="255"
value="<?php echo htmlspecialchars($_POST['email']); ?>">
<?php if($error['email'] == 'blank'): ?>
<p><font color="red">* Input email</font></p>
<?php endif; ?>
</dd>
<dt>password</dt>
<dd>
<input type="password" name="pass" size="35" maxlength="255"
value="<?php echo htmlspecialchars($_POST['pass']); ?>">
<?php if($error['pass'] == 'blank'): ?>
<p><font color="red">* Input password</font></p>
<?php endif; ?>
</dd>
</dl>
<input type="submit" id="login" name="login" value="sigh in">
</form>
Firstly as mentioned in the comments, you are assigning a value in your if statements. Also as a second point I'd guess because your condition is a nested else if the first assignment is always true so the second condition will never be tested.
//form blank check
if ($_POST["email"] = '') {
$error['email'] = "blank";
} else if ($_POST["pass"] = '') {
$error['pass'] = "blank";
}
The second condition statement will only evaluate when the first is false
You should try checking each variable independently nand make sure you use ==
//form blank check
if ($_POST["email"] == '') {
$error['email'] = "blank";
}
if ($_POST["pass"] == '') {
$error['pass'] = "blank";
}

My php is showing validation errors but JS isnt

I am in the early stages of making a registration page for my website. However, the basic form I have created is being validated by javascript and php to ensure the right data will be entered. Even when the javascript is showing no errors and allowing the form to submit, the PHP errors are still being flagged and stopping it. below is the code for the php and html form. Any help will be greatly appreciated, these things are normally a lot easier than anticipated but its driving me crazy as it isnt showing any syntax errors just the errors that i have set up for the user.
The include files just have the mysql password and some basic functions for checking phone numbers.
Thanks in advance
HTML
<?php require_once("functions.inc"); ?>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="register.js"></script>
<link rel="stylesheet" href="form.css">
<title>A Form</title>
</head>
<body>
<form id="userForm" method="POST" action="register-process.php">
<div>
<fieldset>
<legend>Registration Information</legend>
<div id="errorDiv">
<?php
if (isset($_SESSION['error']) && isset($_SESSION['formAttempt'])){
unset($_SESSION['formAttempt']);
print "errors encountered<br>\n";
foreach ($_SESSION['error'] as $error) {
print $error . "<br>\n";
}//end foreach
} // end if
?>
</div>
<label for="fname">First Name:* </label>
<input type="text" id="fname" name="fname">
<span class="errorFeedback errorSpan" id="fnameError">First Name is required</span>
<br>
<label for="name">Last Name:* </label>
<input type="text" id="lname" name="lname">
<span class="errorFeedback errorSpan" id="lnameError">Last Name is required</span>
<br>
<label for="email">Email Address:* </label>
<input type="text" id="email" name="email">
<span class="errorFeedback errorSpan" id="emailError">Email is required</span>
<br>
<label for="password1">Password:* </label>
<input type="password" id="password1" name="password1">
<span class="errorFeedback errorSpan" id="password1Error">Password is required</span>
<br>
<label for="password2">Varify Password:* </label>
<input type="password" id="password2" name="password2">
<span class="errorFeedback errorSpan" id="password2Error">Password's do not match</span>
<br>
<label for="addr">Address: </label>
<input type="text" id="addr" name="addr">
<br>
<label for="city">City: </label>
<input type="text" id="city" name="city">
<br>
<label for="state">State: </label>
<select name="state" id="state">
<option></option>
<option value="AL">Alabama</option>
<option value="CA">California</option>
<option value="CO">Colorado</option>
<option value="FL">Florida</option>
<option value="IL">Illinois</option>
<option value="NJ">New Jersey</option>
<option value="NY">New York</option>
<option value="WI">Winconsin</option>
</select>
<br>
<label for="zip">ZIP: </label>
<input type="text" id="zip" name="zip">
<br>
<label for="phone">Phone Number: </label>
<input type="text" id="phone" name="phone">
<span class="errorFeedback errorSpan" id="phoneError">Format: xxx-xxx-xxxx</span>
<br>
<br>
<label for="work">Number Type:</label>
<input class="radioButton" type="radio" name="phoneType" id="work" value="work">
<label class="radioButton" for="work">Work</label>
<input class="radioButton" type="radio" name="phoneType" id="home" value="home">
<label class="radioButton" for="home">Home</label>
<span class="errorFeedback errorSpan phoneTypeError" id="phoneTypeError">Please Choose an option.</span>
<br>
<input type="submit" id="submit" name="submit">
</fieldset>
</div>
</form>
</body>
PHP register process.php
<?php
require_once('functions.inc');
//prevent access if they havent submitted the form!!
if (!isset($_POST['submit'])) {
die(header("location: register.php"));
}
$_SESSION['formAttempt'] = true;
if (isset($_SESSION['error'])) {
unset($_SESSION['error']);
}
$_SESSION['error'] = array();
$required = array("fname","lname", "email", "password1", "password2");
//check required fields!
foreach ($required as $requiredField) {
if (!isset($_POST[requiredField]) || $_POST[$requiredField] == "") {
$_SESSION['error'][] = $requiredField . " is required.";
}
}
if (!preg_match('/^[\w .]+$/',$_POST['fname'])) {
$_SESSION['error'][] = "Name must be letters and numbers only.";
}
if (!preg_match('/^[\w .]+$/',$_POST['lname'])) {
$_SESSION['error'][] = "Name must be letters and numbers only.";
}
if (isset($_POST['state']) && $_POST['state'] != "") {
if (!isValidState($_POST['state'])) {
$_SESSION['error'][] = "Please choose a valid state";
}
}
if (isset($_POST['zip']) && $_POST['zip'] != "") {
if (!isValidZip($_POST['zip'])) {
$_SESSION['error'][] = "ZIP code error";
}
}
if (isset($_POST['phone']) && $_POST['phone'] != "") {
if (!preg_match('/^[\d]+$/', $_POST['phone'])) {
$_SESSION['error'][] = "Phone numbner should be digits only.";
} else if (strlen($_POST['phone']) < 10 ) {
$_SESSION['error'] = "Phone number should be at least 10 digits.";
}
if (!isset($_POST['phoneType']) || $_POST['phoneType'] == "") {
$_SESSION['error'][] = "Please choose a phone type.";
} else {
$validPhoneTypes = array("work","home");
if (!in_array($_POST['phoneType'], $validPhoneTypes)) {
$_SESSION['error'][] = "Please choose a valid phone type";
}
}
}
if (!filter_var($_POST['email'],FILTER_VALIDATE_URL)) {
$_SESSION['error'][] = "Invalid e-mail address!";
}
if ($_POST['password1'] != $_POST['password2']) {
$_SESSION['error'] = "Passwords do not match";
}
//Final Disposition
if (count($_SESSION['error']) > 0) {
die (header("Location: register.php"));
} else {
if (registerUser($_POST)) {
unset($_SESSION['formAttempt']);
die(header("Location: success.php"));
} else {
error_log("problem registering user: {$_POST['email']}");
$_SESSION['error'][] = "Problem registering account";
die(header("Location: register.php"));
}
}
The extension is the rest of the process php file, i have commented where the errors are coming from.... Thanks Again..
if (count($_SESSION['error']) > 0) {
die (header("Location: register.php"));
} else {
if (registerUser($_POST)) {
unset($_SESSION['formAttempt']);
die(header("Location: success.php"));
} else {
error_log("problem registering user: {$_POST['email']}"); // THIS IS WHERE THE ERROR IS COMNING FROM
$_SESSION['error'][] = "Problem registering account";
die(header("Location: register.php"));
}
}
function registerUser($userData) {
$mysqli = new mysqli(DBHOST,DBUSER,DBPASS,DB);
if ($mysqli->connect_errno) {
error_log("Cannot connect to MySQL: " . $mysqli->connect_error);
return false;
}
$email = $mysqli->real_escape_string($_POST['email']);
//Check for an existing user
$findUser = "SELECT id from Customer where email = '{$email}'";
$findResult = $mysqli->query($findUser);
$findRow = $findResult->fetch_assoc();
if (isset($findRow['id']) && $findRow['id'] != "") {
$_SESSION['error'][] = "A user with that email already exists";
return false;
}
$lastname = $mysqli->real_escape_string($_POST['lname']);
$firstname = $mysqli->real_escape_string($_POST['fname']);
$cryptedPassword = crypt($_POST['password1']);
$password = $mysqli->real_escape_string($cryptedPassword);
if (isset($_POST['addr'])) {
$street = $mysqli->real_escape_string($_POST['addr']);
} else {
$street = "";
}
if (isset($_POST['city'])) {
$city = $mysqli->real_escape_string($_POST['city']);
} else {
$city = "";
}
if (isset($_POST['state'])) {
$state = $mysqli->real_escape_string($_POST['state']);
} else {
$state = "";
}
if (isset($_POST['zip'])) {
$zip = $mysqli->real_escape_string($_POST['zip']);
} else {
$zip = "";
}
if (isset($_POST['phone'])) {
$phone = $mysqli->real_escape_string($_POST['phone']);
} else {
$phone = "";
}
if (isset($_POST['phoneType'])) {
$phoneType = $mysqli->real_escape_string($_POST['phoneType']);
} else {
$phoneType = "";
}
$query = "INSERT INTO Customer (email,create_date,password,last_name,first_name,street,city,state,zip,phone,phone_type) " . "VALUES ('{$email}',NOW(),'{$password}','{$lastname}','{$firstname}'" . ",'{$street}','{$city}','{$zip}','{$phone}','{$phoneType}')";
if ($mysqli->query($query)) {
$id = $mysqli->insert_id;
error_log("inserted {$email} as ID {$id}");
return true;
} else {
error_log("Problem inserting {$query}");
$_SESSION['error'][] = "HERE"; // THIS IS WHERE THE ERROR IS COMNING FROM
return false;
}
}
?>
Your query has a bug in it. Column count isn't the same as value count. You forgot to pass in $state.
$query = "INSERT INTO Customer (email,create_date,password,last_name,first_name,street,city,state,zip,phone,phone_type) " . "VALUES ('{$email}',NOW(),'{$password}','{$lastname}','{$firstname}'" . ",'{$street}','{$city}','{$state}', '{$zip}','{$phone}','{$phoneType}')";
if ($mysqli->query($query)) {
$id = $mysqli->insert_id;
error_log("inserted {$email} as ID {$id}");
return true;
} else {
error_log("Problem inserting {$query}");
error_log("Problem inserting {$mysqli->error}"); // log the error
$_SESSION['error'][] = "HERE"; // THIS IS WHERE THE ERROR IS COMNING FROM
return false;
}

Submiting form, it opens the PHP file?

I will be on the point. But anyways, THANKS IN ADVACE.
So basically When I submit the form I made, it submits and stuff, but it redirects the page to the PHP file, and shows this on the browser (not as an alert) :
{"status":"success","message":"Yer message was sent."}
when the data is successfully validated, and shows this
{"status":"fail","message":"Invalid name provided."}
when the form doesn't validate. What I want, is that when the form submits, it stays on the same page and if status is true or false, it should alert the message in the array.
I'll write down the scripts and the file names are: index.html, script.js and post.php
INDEX.HTML
<form action='post.php' id='post_message' name='post_message' method="post">
<p>
<input id='email' type="email" class='post' placeholder="Email goes in here.(Required) " class="width" name="email">
<br>
<input id='fname' type="text" class='post' placeholder="First Name (Required) " name="FirstName"><br>
<input id='lname' type="text" class='post' placeholder="Last Name (Required) " name="LastName"><br>
<input id='website' type="url" class='post' placeholder="Website? (Optional!)" class="width" name="website"><br>
<textarea id='message_text' placeholder="Your Message goes here. (Required, DUH!) " name='message'></textarea>
</p>
<button type="submit" class="submit" id='btnPost'></button>
<input type="hidden" name="action" value="post_message" id="action">
</form>
SCRIPT.JS
function clearInputs(){
$("#fname").val('');
$("#lname").val('');
$("#email").val('');
$("#website").val('');
$("#message_text").val('');
}
$('#btnPost').click(function() {
var data = $("#post_message").children().serializeArray();
$.post($("#post_message").attr('action'), data, function(json){
if (json.status == "fail") {
alert(json.message);
}
if (json.status == "success") {
alert(json.message);
clearInputs();
}
}, "json");
});
POST.PHP
<?php
if($_POST){
if ($_POST['action'] == 'post_message') {
$fname = htmlspecialchars($_POST['FirstName']);
$lname = htmlspecialchars($_POST['LastName']);
$email = htmlspecialchars($_POST['email']);
$website = htmlspecialchars($_POST['website']);
$message = htmlspecialchars($_POST['message']);
$date = date('F j, Y, g:i a');
if(preg_match('/[^\w\s]/i', $fname) || preg_match('/[^\w\s]/i', $lname)) {
fail('Invalid name provided.');
}
if( empty($fname) || empty($lname) ) {
fail('Please enter a first and last name.');
}
if( empty($message) ) {
fail('Please select a message.');
}
if( empty($email)) {
fail('Please enter an email');
}
$query = "INSERT INTO portmessage SET first_name='$fname', last_name='$lname', email = '$email', website = '$website', message = '$message', date = '$date'";
$result = db_connection($query);
if ($result) {
$msg = "Yer message was sent.";
success($msg);
} else {
fail('Message failed, Please try again.');
}
exit;
}
}
function db_connection($query) {
mysql_connect('127.0.0.1', '######', '####')
OR die(fail('Could not connect to database.'));
mysql_select_db('####');
return mysql_query($query);
}
function fail($message) {
die(json_encode(array('status' => 'fail', 'message' => $message)));
}
function success($message) {
die(json_encode(array('status' => 'success', 'message' => $message)));
}
?>
And yes, it DOES submit the form to the database, but I can't overcome the alert and redirecting problem.
Thanks, again!
You can validate your form client side(using javascript)
HTML
<form action='post.php' id='post_message' name='post_message' method="post" onsubmit="return validate_form();">
Javascript
function validate_form()
{
var success = true;
if($("[name=FirstName]").val() == "")
{
success = false;
}
// your test case goes here
// you can alert here if you find any error
return success;
}

Categories