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>';
} ?>
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>
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>';
}
}
?>
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.
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>