Errors while submitting the form ( php & bootstrap) - php

I'm an intern at the company right now, and I've to create registration and login form for the website.
Currently I'm facing the problem with registration.
this is the errors
I declared everything like in the tutorials but still getting these errors and can't figure out it.
this is the php script:
<?php
//connection to database
include('connection.php');
if ($_SERVER['REQUEST_METHOD']=='POST'){
//Validation for Username
$errors = array();
if(empty($_POST['user_name'])){
$errors['user_name'] = 'Please fill in your Username';//Username
}else{
$user_name = mysqli_real_escape_string($con, trim($_POST['user_name']));
//validation to check if the username posted is in use.
if($check = $connection->query("SELECT * FROM student WHERE username = '$user_name'")){
if($check->num_rows){
$errors['user_name'] = 'Username in use';
}
}else{
$errors['user_name'] = 'the query did not work';
}
}
//validation for password
if(empty($_POST['pword'])){
$errors['pword'] = 'Please fill in password';
}else{
$pword = $_POST['pword'];
}
//checking if the password ented in verify password is matching the password field
if(empty($_POST['pwordConfirm'])){
$errors['pwordConfirm'] = 'Please verify password';
}else{
$pwordConfirm = $_POST['pwordConfirm'];
if($pword!=$pwordConfirm){
$errors ['pwordConfirm'] = 'passwords do not match';
}else{
$password = mysqli_real_escape_string($connection,trim($_POST['pword']));
// $password = sha1($password);
}
}
// validation for name textfield
if(empty($_POST['fname'])){
$errors['fname'] = 'Please fill in your name ';
}else{
$fname = mysqli_real_escape_string($connection,trim($_POST['customer_name']));
}
// validation for passport textfield
if(empty($_POST['passport'])){
$errors['passport'] = 'Please fill in your passport ';
}else{
$passport = mysqli_real_escape_string($connection,trim($_POST['passport']));
}
//validation for email
if(empty($_POST['email'])){
$errors['email'] = 'Please fill in your email';
}else{
$email = mysqli_real_escape_string($connection,trim($_POST['email']));
if($check = $connection->query("SELECT * FROM customer WHERE email = '$email'")){
if($check->num_rows){
$errors['email'] = 'Email in use';
}
}else{
$errors['email'] = 'the query did not work';
}
}
//validation for phone no
if(empty($_POST['mobinput'])){
$errors['mobinput'] = 'Please fill in your phone';
}else{
$mobinput = mysqli_real_escape_string($connection,trim($_POST['mobinput']));
}
//validation for phone no
if(empty($_POST['homemobinput'])){
$errors['homemobinput'] = 'Please fill in your phone';
}else{
$homemobinput = mysqli_real_escape_string($connection,trim($_POST['homemobinput']));
}
//validation for phone no
if(empty($_POST['dob'])){
$errors['dob'] = 'Please fill in your phone';
}else{
$dob = mysqli_real_escape_string($connection,trim($_POST['dob']));
}
//validation for gender column to be selected.
if(empty($_POST['sex'])){
$errors['sex'] = 'Please fill in your gender';
}else{
if( $_POST['sex'] == 'default')
{
$errors['sex'] = 'Please select your gender';
}
else{
$gender = mysqli_real_escape_string($connection,trim($_POST['sex']));
}
}
//validation for mstatus
if(empty($_POST['mstatus'])){
$errors['mstatus'] = 'Please fill in your phone';
}else{
$mstatus = mysqli_real_escape_string($connection,trim($_POST['mstatus']));
}
//validation for education
if(empty($_POST['education'])){
$errors['education'] = 'Please fill in your phone';
}else{
$education = mysqli_real_escape_string($connection,trim($_POST['education']));
}
//validation for occupation
if(empty($_POST['occupation'])){
$errors['occupation'] = 'Please fill in your phone';
}else{
$occupation = mysqli_real_escape_string($connection,trim($_POST['occupation']));
}
//validation for address
if(empty($_POST['address'])){
$errors['address'] = 'Please fill in your address';
}else{
$address = mysqli_real_escape_string($connection,trim($_POST['address']));
}
//validation for wmcauin
if(empty($_POST['wmcauin'])){
$errors['wmcauin'] = 'Please fill in your phone';
}else{
$wmcauin = mysqli_real_escape_string($connection,trim($_POST['wmcauin']));
}
//validation for tp
if(empty($_POST['tp'])){
$errors['tp'] = 'Please fill in your phone';
}else{
$tp = mysqli_real_escape_string($connection,trim($_POST['tp']));
}
//validation for wauinmassage
if(empty($_POST['wauinmassage'])){
$errors['wauinmassage'] = 'Please fill in your phone';
}else{
$wauinmassage = mysqli_real_escape_string($connection,trim($_POST['wauinmassage']));
}
//validation for hduhabttbc
if(empty($_POST['hduhabttbc'])){
$errors['hduhabttbc'] = 'Please fill in your phone';
}else{
$hduhabttbc = mysqli_real_escape_string($connection,trim($_POST['hduhabttbc']));
}
if(empty($errors)){
$query = "INSERT INTO student ";
$query .= "(`Student_id`, `Full_Name`, `Adress`, `Ic_Passport_no`, `Date_of_Birth`, `Mobile_No`, `Home_No`,
`Email`, `Marital_status`, `Occupation`, `Education`, `Why_interest_in_Massage`, `How_did_you_know_about_us`,
`Registration_date`, `Traner_Preference`, `course_of_interest`, `gender`, `username`, `password`, `user_type`) ";
$query .= "VALUES ('','$fname','$address','$sex','$passport','$dob','$mobinput','$homemobinput',
'$email', '$mstatus', '$occupation', '$education', '$wauinmassage','$hduhabttbc',
'', '$tp', '$wmcauin','$sex', '$user_name', '$password', 'S' )";
$register = $connection->query($query);
$customer_id = $connection->query("SELECT customer_id FROM customer WHERE email = '$email' and user_name = '$user_name'")->fetch_object()->customer_id;
$query1 = "INSERT INTO cart ";
$query1 .= "(customer_id) ";
$query1 .= "VALUES ('customer_id')";
$addCart = $connection->query($query1);
if(!$register && !addCart){
echo $query;
}
else
{
$message = 'Registration successfully completed, You can now login';
}
}}?>
This is the html form:
<!-- PopUp registration Form -->
<div id="signup" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- PopUp registration Form content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Massage Course Registration Form</h4>
</div>
<div class="modal-body">
<form method="post" class="form-signin form-group">
<label for="usernameInput" class="usernameinput">Username</label>
<input type="text" class="form-control" id="user_name" name="user_name">
<br>
<label for="passwordinput">Password</label>
<input type="password" class="form-control" id="passwordinput" name="pword">
<br>
<br>
<label for="NameInput">Name</label>
<input type="text" class="form-control" id="InputName" placeholder="Jane Doe" name="fname">
<br>
<label for="ICinput">I.C/Passport No.</label>
<input type="text" class="form-control" id="ICinput" name="passport">
<br>
<label for="EmailInput">Email</label>
<input type="email" class="form-control" id="EmailInput" placeholder="jane.doe#example.com" name="email">
<br>
<label for="mobinput">Mobile No</label>
<input type="number_format" class="form-control" id="mobinput" name="mobinput">
<br>
<label for="homemobinput">Home No</label>
<input type="number_format" class="form-control" id="homemobinput" name="homemobinput">
<br>
<label for="DOBinput">Date of Birth</label>
<input type="date" class="form-control" id="DOBinput" name="dob">
<br>
<label for="SexInput">sex</label>
<select class="form-control" id="SexInput" name="sex">
<option>Male</option>
<option>Female</option>
</select>
<br>
<label for="MaritalStatusInput">Marital Status</label>
<select class="form-control" id="MaritalStatusInput" name="mstatus">
<option>Single</option>
<option>Married</option>
<option>Divorced</option>
<option>Widowed</option>
</select>
<br>
<label for="EducationInput">Education</label>
<input type="text" class="form-control" id="EducationInput" name="education">
<br>
<label for="OccupationInput">Occupation</label>
<input type="text" class="form-control" id="OccupationInput" name="occupation">
<br>
<label for="Addressinput">Address</label>
<input type="text" class="form-control" id="Addressinput" name="address">
<br>
<label for="CourseSelection">Which massage course are you interested in?</label>
<select class="form-control selectpicker" id="CourseSelection" name="wmcauin">
<optgroup label="Professional">
<option>Full Body Massage</option>
<option>Reflexology Course</option>
<option>Aromatherapy Course</option>
</optgroup>
<optgroup label="Advanced">
<option>Pre and Post Natal</option>
<option>Slimming Massage</option>
<option>Lymphatic Drainage</option>
<option>Spa and Facial</option>
<option> Raindrop Techniques</option>
<option>Male Health</option>
<option>Sport Injury</option>
<option>Traditional Malay</option>
</optgroup>
</select>
<br>
<label for="TrainerPreferenceInput">Trainer Preference</label>
<select class="form-control" id="TrainerPreferenceInput" name="tp">
<option>Male Trainer</option>
<option>Female Trainer</option>
</select>
<br>
<label for="InterestFeedbackInput">Why are you interedted in Massage?</label>
<input type="text" class="form-control" id="InterestFeedback" name="wauinmassage">
<br>
<label for="ReferalFeedbackInput">How did you heard about Tim BodyCare Training Centre</label>
<input type="text" class="form-control" id="ReferalFeedbackInput" name="hduhabttbc">
<div class="form-group">
<button type="submit" class="btn btn-primary" name="btn-signup">
<i class="glyphicon glyphicon-open-file"></i> SIGN UP
</button>
</div>
</form>
<div class="modal-footer">
<p>By clicking submit, you agreeing with our terms and conditions</p>
</div>
</div>
</div>
</div>
<!-- End of PopUp registration Form -->
Note that php script and html form all in one file.

Change the variable name in training_index.php
$conn and $connection to $conn
Because in connection.php file you mentioned your db connection variable name as
$con = new mysqli($servername, $username, $password, $dbname);

Related

Cannot display alert once the user login inputs incorrect credentials PHP PDO

index.php
This is the login form
<div class="modal-body">
<form action="loginPDO.php" method="post">
<?php if(isset($message))
{
echo '<label class="text-danger">'.$message.'</label>';
} ?>
<div class="form-group">
<label for="recipient-name" class="col-form-label">Username:</label>
<input type="text" name="username" id="username" placeholder="Enter Username" class="form-control">
</div>
<div class="form-group">
<label for="message-text" class="col-form-label">Password:</label>
<input type="password" name="password" id="password" placeholder="Enter Password" class="form-control">
</div>
<div class="form-group">
<button type="submit" name="login" id="login" class="btn btn-primary">Login</button>
<button type="button" class="btn btn-info">Register</button>
</div>
</form>
</div>
loginPDO.php
<?php
include 'dbconnection.php';
if(isset($_POST["login"]))
{
if(empty($_POST["username"]) || empty($_POST["password"]))
{
$message = '<label>All fields are required</label>';
header("location:index.php");
}
else
{
$query = "SELECT * FROM users WHERE username = :username AND password = :password";
$statement = $conn->prepare($query);
$statement->execute(
array(
'username' => $_POST["username"],
'password' => $_POST["password"]
)
);
$count = $statement->rowCount();
if($count > 0)
{
$_SESSION["username"] = $_POST["username"];
header("location:dashboard.php");
}
else
{
$message = '<label>Wrong Data</label>';
header("location:index.php");
}
}
}
?>
Hi Guys, I want to know how to display the alert message once the user inputs incorrect credentials
For example, Imagine the user inputs wrong credentials once the user clicks the login button it automatically appears the alert message above Username.
$message just exists in file loginPDO.php and ...
$message = '<label>Wrong Data</label>';
header("location:index.php");
Is not sufficient to pass the $message variable to index.php.
As said in comments you can try
// file loginPDO.php
$message = '<label>Wrong Data</label>';
header("location:index.php?error=" . urlencode("Wrong Data"));
// file index.php
<?php
$message = isset($_GET['error']) ? $_GET['error'] : null; // get the error from the url
if(!empty($message)) {
echo '<label class="text-danger">'.$message.'</label>';
} ?>

User registration form not working as it such php

I have create a form with html and php that allows a user to create an account and their information is stored within a mysql database.
The forms works and the user is able to create an account. However if the user clicks the submit button without filling in the form it seems to display that the email address has already been added.
I can't seem to see what is wrong.
My php code
<?php
session_start();
error_reporting(E_ALL); ini_set('display_errors', 1);
include "connect.php";
if (isset($_POST["submit"])) {
$error = array(); // Declare An Array to store any error message
$title = $_POST['title'];
$address2 = $_POST['up_address2'];
if(empty($_POST['up_first_name'])) { // if no name has been supplied
$error[] = 'Please Enter Your First Name'; // add to array "error"
} else {
$firstName = $_POST['up_first_name']; // else assign it to a variable
}
if(empty($_POST['up_last_name'])) { // if no name has been supplied
$error[] = 'Please Enter Your Last Name'; // add to array "error"
} else {
$lastName = $_POST['up_last_name']; // else assign it to a variable
}
if(empty($_POST['up_email'])) { // if no name has been supplied
$error[] = 'Please Enter Your Email'; // add to array "error"
} else {
if (preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*#([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/", $_POST['up_email'])) {
// regular expression for email validation
$email = $_POST['up_email'];
} else {
$error[] = 'Your email is invalid';
}
}
if(empty($_POST['up_password'])) {
$error[] = 'Please Enter Your Password';
} else {
$password = $_POST['up_password'];
}
if(empty($_POST['up_date_of_birth'])) {
$error[] = 'Please Enter Your Date Of Birth';
} else {
$dateOfBirth = $_POST['up_date_of_birth'];
}
if(empty($_POST['up_number'])) {
$error[] = 'Please Enter Your Contact Number';
} else {
$number = $_POST['up_number'];
}
if(empty($_POST['up_address'])) {
$error[] = 'Please Enter Your First Line of Your Address';
} else {
$address = $_POST['up_address'];
}
if(empty($_POST['up_country'])) {
$error[] = 'Please Enter Your Home Country';
} else {
$country = $_POST['up_country'];
}
if(empty($_POST['up_postcode'])) {
$error[] = 'Please Enter Your Postcode';
} else {
$postcode = $_POST['up_postcode'];
}
if(empty($error)) // send to Database if there's no error
{
// If everything is ok...
// Make sure the email address is avilable:
$query_verify_email = "SELECT * FROM user WHERE Email ='$email'";
$result_verify_email = mysqli_query($con, $query_verify_email);
if(!$result_verify_email) {
echo 'Database Error Occured';
}
if (mysqli_num_rows($result_verify_email) == 0) { // IF no previous user is using this email.
$query_insert_user = "INSERT INTO user (Title, FirstName, LastName, Email, Password, DataOfBirth, ContactNumber, Address, Address2, Country, Postcode)VALUES ('$title', '$firstName', '$lastName', '$email', '$password', '$dateOfBirth', '$number', '$address', '$address2', '$country', '$postcode')";
$result_insert_user = mysqli_query($con, $query_insert_user);
if (!$result_insert_user) {
echo 'Query Failed ';
}
} else { // If it did not run OK.
echo '<div class="errormsgbox">You could not be registered due to a system </div>';
}
} else { // The email address is not available.
echo '<div class="errormsgbox" >That email address has already been registered.</div>';
}
}
?>
My html form
<form name="signup" id="signup" action="create_account.php" method="post">
<label for="title">Title</label>
<select name="title" id="title">
<option value="Mr">Mr</option>
<option value="Miss">Miss</option>
<option value="Mrs">Mrs</option>
<option value="Ms">Ms</option>
<option value="Dr">Dr</option>
</select>
<br>
<label for="up_first_name">First Name</label>
<input type="text" name="up_first_name" id="up_first_name" placeholder="First Name" />
<br>
<label for="up_last_name">Last Name</label>
<input type="text" name="up_last_name" id="up_last_name" placeholder="Last Name" />
<br>
<label for="up_email"> Email</label>
<input type="email" name="up_email" id="up_email" placeholder="username#email.com" />
<br>
<label for="up_password">Password</label>
<input type="password" name="up_password" id="up_password" placeholder="Password" />
<br>
<label for="up_date_of_birth">Date Of Birth</label>
<input type="text" name="up_date_of_birth" id="up_date_of_birth" placeholder="dd/mm/yyyy" />
<br>
<label for="up_number">Contact Number</label>
<input type="text" name="up_number" id="up_number" placeholder="+44 0000 000000" />
<br>
<label for="up_address">Address</label>
<input type="text" name="up_address" id="up_address" placeholder="Address" />
<br>
<label for="up_address2">Address 2 (optional)</label>
<input type="text" name="up_address2" id="up_address2" placeholder="Address 2" />
<br>
<label for="up_country">Country</label>
<input type="text" name="up_country" id="up_country" placeholder="Address 2" />
<br>
<label for="up_postcode">Postcode</label>
<input type="text" name="up_postcode" id="up_postcode" placeholder="Postcode" />
<br>
<input id="submit" name="submit" type="submit" value="Register My Account" id="myButton" class="btn btn-primary"/>
</form>

Instead of a div being shown, the form is sent

The following should output a div if the data is not entered in the input fields or if the passwords don't match, but it does not happen:
<?php
$data = $_POST;
if(isset($data['action_signup'])){
$errors = array();
if(trim($data['email'])==''){
$errors[] = 'Введите email';
}
if(trim($data['login'])==''){
$errors[] = 'Введите имя пользователя';
}
if($data['password']==''){
$errors[] = 'Введите пароль';
}
if($data['enterpassword'] != $data['password']){
$errors[] = 'Пароль введен не верно';
}
if(empty($errors)){
//Все заебись
}else{
echo '<div class="error_div">'.array_shift($errors).'</div>';
}
}
?>
Form:
<form action="/Register.php" method="post">
<div class="containerForTextRegister"><a class="register">РЕГИСТРАЦИЯ</a>
</div>
<div class="container_inputs">
<input class="register_input_email" name="email" placeholder="e-mail" required type="email" maxlength="40" value="<?php echo #$data['email'];?>">
<input class="register_input_login" name="login" placeholder="login" required maxlength="12" value="<?php echo #$data['login'];?>">
<input class="register_input_password" name="password" placeholder="password" required pattern="^[a-zA-Z]+$" maxlength="30">
<input class="register_input_enterpassword" name="enterpassword" placeholder="enter password" required pattern="^[a-zA-Z]+$" maxlength="30">
<div class="buttons_container">
<button class="button_entrance"><a class="text_button_entrance">войти</a></button>
<button class="button_register"><a class="text_button_register" name="action_signup">регистрация</a></button>
</div>
</div>
</form>
A div window should appear, but the data is just sent and that’s it. Help, I will be very grateful
You have to change your html code <button class="button_register"><a class="text_button_register" name="action_signup">регистрация</a></button> to
Or
if(isset($data['action_signup'])) to if(isset($data['email']))
like
<?php
$data = $_POST;
if(isset($data['email'])){
$errors = array();
if(trim($data['email'])==''){
$errors[] = 'Введите email';
}
if(trim($data['login'])==''){
$errors[] = 'Введите имя пользователя';
}
if($data['password']==''){
$errors[] = 'Введите пароль';
}
if($data['enterpassword'] != $data['password']){
$errors[] = 'Пароль введен не верно';
}
if(empty($errors)){
//Все заебись
}else{
echo '<div class="error_div">'.array_shift($errors).'</div>';
}
}
?>

Submit form (contact form) that links with my SQL database and replaces the submission form with a message on the same page via AJAX

I want to create a submit form (contact form) that links with my SQL database and replaces the submission form with a message on the same page via AJAX. I've tried W3C schools and a couple of step by step guides but still struggling. So far, I've written the HTML for and Validation and connected to my SQL database. However, I'm not sure what steps to take next. I'm new to coding and not sure what to do next...
<?php
// define variables and set to empty values
$nameErr = $emailErr = $phoneErr = "";
$name = $email = $phone = $comment = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
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 = "Invalid email format";
}
}
if (empty($_POST["phone"])) {
$phoneErr = "Telephone is required";
} else {
$phone = test_input($_POST["phone"]);
}
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<div id="form">
<form method="post" action="<?php echo htmlspecialchars($_SERVER["register.php"])?>">
<fieldset>
Name: <input type="text" name="name" value="<?php echo $name;?>">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail: <input type="text" name="email" value="<?php echo $email;?>">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Phone: <input type="tel" name="phone" value="<?php echo $phone;?>">
<span class="error">* <?php echo $phoneErr;?></span>
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"><?php echo $comment;?></textarea>
<br><br>
<button type="submit"> Submit</button>
</fieldset>
</form>
</div>
I will do it simply like this:
Create an empty div before Form's fieldset:
<div class="col-xs-12 col-sm-9 col-md-8 col-lg-8 conForm">
<h4>Shoot a message!</h4>
**<div id="message"></div>**
<form method="post" action="php/contact.php" name="cform" id="cform">
<input name="name" id="name" type="text" class="col-xs-12 col-sm-6 col-md-6 col-lg-6" placeholder="Your name..." >
<input name="email" id="email" type="email" class=" col-xs-12 col-sm-6 col-md-6 col-lg-6 noMarr" placeholder="Your email..." >
<textarea name="comments" id="comments" cols="" rows="" class="col-xs-12 col-sm-12 col-md-12 col-lg-12" placeholder="Your message..."></textarea>
<input type="submit" id="submit" name="submit" class="submitBnt" value="Send message">
<div id="simple-msg"></div>
</form>
</div>
in PHP print message like this after email sent:
if(mail($address, $e_subject, $msg, $headers)) {
// Email has sent successfully, echo a success page.
echo "<fieldset>";
echo "<div id='success_page'>";
echo "<h3>Email Sent Successfully.</h3>";
echo "<p>Thank you <strong>$name</strong>, your message has been submitted to us.</p>";
echo "</div>";
echo "</fieldset>";
} else {
echo 'ERROR!';
}
As you asked, i think you are totally new in coding world.so that's why i write full code in one page. create a .php file and paste this code
<html>
<head>
<script type="text/javascript">
function validateName() {
var name = document.getElementById('contact-name').value;
if(name.length == 0) {
producePrompt('Name is required', 'name-error' , 'red')
return false; }
if (!name.match(/^[A-Za-z]*\s{1}[A-Za-z]*$/)) {
producePrompt('First and last name, please.','name-error', 'red');
return false; }
producePrompt('Valid', 'name-error', 'green');
return true;}
function validatePhone() {
var phone = document.getElementById('contact-phone').value;
if(phone.length == 0) {
producePrompt('Phone number is required.', 'phone-error', 'red');
return false; }
if(phone.length != 10) {
producePrompt('Include area code.', 'phone-error', 'red');
return false; }
if(!phone.match(/^[0-9]{10}$/)) {
producePrompt('Only digits, please.' ,'phone-error', 'red');
return false; }
producePrompt('Valid', 'phone-error', 'green');
return true;}
function validateEmail () {
var email = document.getElementById('contact-email').value;
if(email.length == 0) {
producePrompt('Email Invalid','email-error', 'red');
return false; }
if(!email.match(/^[A-Za-z\._\-[0-9]*[#][A-Za-z]*[\.][a-z]{2,4}$/)) {
producePrompt('Email Invalid', 'email-error', 'red');
return false; }
producePrompt('Valid', 'email-error', 'green');
return true;}
function validateMessage() {
var message = document.getElementById('contact-message').value;
var required = 10;
var left = required - message.length;
if (left > 0) {
producePrompt(left + ' more characters required','message-error','red');
return false; }
producePrompt('Valid', 'message-error', 'green');
return true;}
function validateForm() {
if (!validateName() || !validatePhone() || !validateEmail() || !validateMessage()) {
jsShow('submit-error');
producePrompt('Please fix errors to submit.', 'submit-error', 'red');
setTimeout(function(){jsHide('submit-error');}, 2000);
return false; } else { }
}
function jsShow(id) {
document.getElementById(id).style.display = 'block'; }
function jsHide(id) {
document.getElementById(id).style.display = 'none';}
function producePrompt(message, promptLocation, color) {
document.getElementById(promptLocation).innerHTML = message;
document.getElementById(promptLocation).style.color = color;}
</script>
</head>
<form action="" method="POST">
<div class="form-group">
<label for="contact-name">Name</label>
<input type="text" class="form-control" id="contact-name" name="name" placeholder="Enter your name.." onkeyup='validateName()'>
<span class='error-message' id='name-error'></span>
</div>
<div class="form-group">
<label for="contact-phone">Phone Number</label>
<input type="tel" class="form-control" id="contact-phone" name="phone" placeholder="Ex: 1231231234" onkeyup='validatePhone()'>
<span class='error-message' id='phone-error'></span>
</div>
<div class="form-group">
<label for="contact-email">Email address</label>
<input type="email" class="form-control" id="contact-email" name="email" placeholder="Enter Email" onkeyup='validateEmail()'>
<span class='error-message' id='email-error'></span>
</div>
<div class="form-group">
<label for='contactMessage'>Your Message</label>
<textarea class="form-control" rows="5" id='contact-message' name='message' placeholder="Enter a brief message" onkeyup='validateMessage()'></textarea>
<span class='error-message' id='message-error'></span>
</div>
<button onclick='return validateForm()' name="submit" value="submit" class="btn btn-default">Submit</button>
<span class='error-message' id='submit-error'></span>
<span class='success-message' id='submit-success'></span>
<?php
if (isset($_POST['submit']) && (!empty($_POST['submit']))) {
$servername = "localhost";
$username = "root"; //change this to your username
$password = ""; //change this to your database password
$dbname = "db"; //change this to your database name
$name = "$_POST[name]";
$phone = "$_POST[phone]";
$email = "$_POST[email]";
$message = "$_POST[message]";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error){
die("Connection failed:".$conn->connect_error);}
//insert data into table named guestbook
$sql = "INSERT INTO guestbook (name, email, phone, message) VALUES ('$name', '$email', '$phone', '$message')";
if ($conn->query($sql) === TRUE) {
echo "<br/><font color=green>Your Comment Successfully Sent</font>";
} else {
echo "Error updating record: " . $conn->error; }
$conn->close();}
?>
</form>
</body>
</html>
In your DATABASE, create a database whatever you named but dont forget to change in php file $dbname = ""; and create table with these code:
CREATE TABLE guestbook
(
id int NOT NULL AUTO_INCREMENT,
name varchar(255),
email varchar(255),
phone varchar(255),
message varchar(255),
PRIMARY KEY (id)
);
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error){
die("Connection failed:".$conn->connect_error);
}
$sql = "INSERT INTO MyGuests (name, email, phonenumber,comment)
VALUES ($name , $email ,$phone,$comment)";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: ".$sql."<br>".$conn->error;
}
$conn->close();
Where put you $comment , $name and others and also configure you database name, password and database table.

Forgot password reset not displaying correct email address and not updating password if any error made by user during for submission

I am currently working on PHP forgot password reset, which partially doing the job but seeking some assistance to improve it further.
1st issue: It is not displaying the correct email address on the
submission form. It updates the password correctly but doesn't
display correct email address.
2nd issue: Also if the user makes an error while submitting the form on reloading the page doesn't update the password hence the user has to go back to his email to click back on the link.
<?php
include('../config/connection.php');
if(isset($_POST['submit'])){
$password = mysqli_real_escape_string($dbc,$_POST['password']);
$Rpassword = mysqli_real_escape_string($dbc,$_POST['Rpassword']);
$acode=$_POST['encrypt'];
$passmd = md5(SHA1($password));
if (empty($password) OR empty($Rpassword)) {
$error = 'One or either field is missing';
} if ($password != $Rpassword) {
$error = 'Passwords don\'t match';
} if(strlen($password)<6 OR strlen($Rpassword)>20) {
$error = 'Password must be between 6 to 20 characters';
}
else {
$query = mysqli_query($dbc,"select * from users where passreset='$acode'") or die(mysqli_error($dbc));
if (mysqli_num_rows ($query)==1)
{
$query3 = mysqli_query($dbc,"UPDATE users SET password='$passmd',passreset=0 WHERE passreset='$acode'")
or die(mysqli_error($dbc));
$sent = 'Password has been Changed successfully, Please sign in for loging in.';
}
else
{
$error = 'Please click back on the Forgot password link to reset your password ';
}
}
}
?>
<body>
<?php if(!isset($_POST['submit']) OR $error != '' OR isset($error)) { ?>
<?php if(isset($error) AND $error !='')
{
echo '<p style="color:#c43235">'.$error.'</p>';
}
?>
<form action="reset.php" method="post" role="form">
<div class="form-group">
<label for="password">Email</label>
<input type="text" class="form-control" id="email" name="email" value="
<?php
$acode=$_POST['encrypt'];
$query5 = mysqli_query($dbc,"SELECT * FROM users where passreset='$acode'") or die(mysqli_error($dbc));
$list = mysqli_fetch_array($query5); /* Error-----*/
$val = $list['email'];
echo $val;?>" >
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" id="password" name="password" placeholder="Password" >
</div>
<div class="form-group">
<label for="password">Re-enter Password</label>
<input type="password" class="form-control" id="password" name="Rpassword" placeholder="Password" >
</div>
<input type="hidden" class="form-control" name="encrypt" value="<?php echo $_GET['encrypt'];?>" >
<button class="btn btn-success" type="submit" name="submit" />Submit</button>
</form>

Categories