PHP registration form will not submit - php

Here is my code,
HTML:
<div class="form-content">
<form method="post" action="../controller/regprocess.php">
<div class="form-group">
<label>Username</label>
<input type="text" id="Rusername" name="Rusername" required="required" />
</div>
<div class="form-group">
<label>Password</label>
<input type="password" id="Rpassword" name="Rpassword" required="required" />
</div>
<div class="form-group">
<label>First Name</label>
<input type="text" id="RfirstName" name="RfirstName" required="required" />
</div>
<div class="form-group">
<label>Last Name</label>
<input type="text" id="RlastName" name="RlastName" />
</div>
<div class="form-group">
<label>Email</label>
<input type="email" id="Remail" name="Remail" required="required" />
</div>
<div class="form-group">
<label>Phone</label>
<input type='number' id="Rphone" name="Rphone" required="required" />
</div>
<div class="form-group">
<button type="submit">Register</button>
</div>
</form>
</div>
regprocess PHP:
<?PHP
session_start();
//connect to the database
require('../model/database.php');
//Load user functions
require('../model/functions_users.php');
//retrieve the registration details into the form
$username = $_POST['Rusername'];
$password = $_POST['Rpassword'];
$firstName = $_POST['RfirstName'];
$lastName = $_POST['RlastName'];
$email = $_POST['Remail'];
$phone = $_POST['Rphone'];
//call the add_user() function
$result = add_user($username, $password, $firstName, $lastName, $email, $phone);
//create user messages
if($result)
{
//create a success message to display on page
$_SESSION['success'] = 'Thank you for creating an account. Please login.';
//redirect to products.php
header('location: ../view/login-registration.php?page=login');
}
else
{
//create a error message to display on page
$_SESSION['error'] = 'An error has occurred. Please try again.';
//redirect to product_add_form.php
header('location: ../view/login-registration.php?page=login');
}?>
and finally my result function:
function add_user($username, $password, $firstName, $lastName, $email, $phone)
{
global $conn;
$sql = "INSERT INTO users (username, password, firstName, lastName, email, phone) VALUES (:username, :password, :firstName, :lastName, :email, :phone)";
$statement = $conn->prepare($sql);
$statement->bindValue(':username', $username);
$statement->bindValue(':password', $password);
$statement->bindValue(':firstName', $firstName);
$statement->bindValue(':lastName', $lastName);
$statement->bindValue(':email', $email);
$statement->bindValue(':phone', $phone);
$result = $statement->execute();
$statement->closeCursor();
return $result;
}
I have two parent divs overlapping each other, one is hidden (registration form) until a panel is clicked and sets div active to appear on top of the login form. The active div (login form) submit button works but the 2nd form (registration form) submit button does not work.
JS:
$(document).ready(function() {
var panelOne = $('.form-panel.two').height(),
panelTwo = $('.form-panel.two')[0].scrollHeight;
$('.form-panel.two').not('.form-panel.two.active').on('click', function(e) {
e.preventDefault();
$('.form-toggle').addClass('visible');
$('.form-panel.one').addClass('hidden');
$('.form-panel.two').addClass('active');
$('.form').animate({'height': panelTwo
}, 200);
});
$('.form-toggle').on('click', function(e) {
e.preventDefault();
$(this).removeClass('visible');
$('.form-panel.one').removeClass('hidden');
$('.form-panel.two').removeClass('active');
$('.form').animate({
'height': panelOne
}, 200);
});
});

$('.form-panel.two').not('.form-panel.two.active').on('click', function(e) {
/*e.preventDefault(); --> it looks like this is what is preventing your form submission but it is hard to tell without the full file and error log */
$('.form-toggle').addClass('visible');
$('.form-panel.one').addClass('hidden');
$('.form-panel.two').addClass('active');
$('.form').animate({'height': panelTwo
}, 200);
});

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

PDO not inputting form data into database

I'm trying to input form data into the database. I'm using almost the same code as I did for my registration script, which works perfectly. I'm completely stumped at this point.
I have error reporting turned on for PHP and PDO, nothing is happening. When the form is sent, it appears to work (except without the confirmation messages appearing) but nothing is entered into the database.
I have two files, request.php (the form) and parseRequest.php (the backend to the form).
request.php
<form action="" method="post">
<div class="form-group">
<input type="hidden" class="form-control" name="username" id="usernameField" value="<?php echo $_SESSION['username'];?>">
</div>
<div class="form-group">
<label>Headlining Band/Artist</label>
<input type="text" class="form-control" name="artist" id="artistField" placeholder="Artist">
</div>
<div class="form-group">
<label>Date</label>
<input type="text" class="form-control" name="day" id="dateField" placeholder="MM/DD/YYYY">
</div>
<div class="form-group">
<label>Venue</label>
<input type="text" class="form-control" name="venue" id="venueField" placeholder="Venue">
</div>
<div class="form-group">
<label>City, State</label>
<input type="text" class="form-control" name="city" id="cityField" placeholder="City, State">
</div>
<input type="hidden" name="token" value="<?php if(function_exists('_token')) echo _token(); ?>">
<button type="submit" name="requestBtn" class="btn btn-primary pull-right">Submit</button>
parseRequest.php
<?php
include_once 'resource/Database.php';
include_once 'resource/utilities.php';
include_once 'resource/send-email.php';
// Processing the form
if(isset($_POST['requestBtn'], $_POST['token'])){
if(validate_token($_POST['token'])) {
//process form here
$form_errors = "";
// validation
$required_fields = array('artist', 'day', 'venue', 'city');
// check empty fieldset
$form_errors = check_empty_fields($required_fields);
// date check
$fields_to_check_length = array('day' => 10);
//call the function to check minimum required length and merge the return data into form_error array
$form_errors = array_merge($form_errors, check_min_length($fields_to_check_length));
// collect data
$username = $_POST['username'];
$artist = $_POST['artist'];
$day = $_POST['day'];
$venue = $_POST['venue'];
$city = $_POST['city'];
}
else if(empty($form_errors))
{
// preparing and inputting data
try
{
$sqlInsert = "INSERT INTO requests(username, artist, day, venue, city)
VALUES (:username, :artist, :day, :venue, :city)";
//use PDO prepared to sanitize data
$statement = $db->prepare($sqlInsert);
//add the data into the database
$statement->execute(array(':username' => $username, ':artist' => $artist, ':day' => $day, ':venue' => $venue, ':city' => $city));
// email confirmation
$addresses = array($_SESSION['email'], 'codylkaczynski#gmail.com');
//prepare email body
$mail_body = '<html>
<body style="font-family: Arial, Helvetica, sans-serif;
line-height:1.8em;">
<h2>Amped Sound Staff Portal: Request Received</h2>
<p>Dear '.$username.'<br><br>
Your request for the '.$artist.' show in '.$city.' on '.$date.' has been received!</p><br/>
<p>We will let you know if your request has been approved or denied ASAP.</p><br/>
<p>Thank you!</p><br/>
<p><strong>©2018 Amped Sound</strong></p>
</body>
</html>';
$namejeff = explode(',', $addresses);
foreach ($addresses as $address)
{
$mail->AddAddress($address);
$mail->Subject = "Request Received!";
$mail->Body = $mail_body;
}
//Error Handling for PHPMailer
if(!$mail->Send())
{
$result = "<script type=\"text/javascript\">swal(\"Error\",\" Email sending failed: $mail->ErrorInfo \",\"error\");</script>";
}
else
{
$result = "<script type=\"text/javascript\">
swal({
title: \"Request received!\",
text: \"We have received your request! Please check your email for confirmation.\",
type: 'success',
confirmButtonText: \"Thank You!\" });
</script>";
}
}
catch (PDOException $ex)
{
$result = flashMessage("An error occurred: " .$ex->getMessage());
}
}
}
I appreciate any help I can get. I've tried a bunch of solutions I found on StackOverflow already, to no avail.

My php vairables are not working properly beacuse of jQuery

Whenever I hit submit button my first name, last name and email are empty even when they are filled up properly so they return red color fonts.
Here is the PHP code:
<?php
if (isset($_POST['submit'])) {
include_once 'dbh.inc.php';
$first = mysqli_real_escape_string($conn, $_POST['first']);
$last = mysqli_real_escape_string($conn, $_POST['last']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$college = mysqli_real_escape_string($conn, $_POST['college']);
$pwd = mysqli_real_escape_string($conn, $_POST['password']);
// Error handlers
$errorfirst=false;
$erroremail=false;
$errorlast=false;
$errorpwd=false;
// Check for empty fields
if (empty($first) || empty($email) || empty($pwd)) {
echo "
<span class='form-error'>*Please check one of the fields before submitting<br></span>
<span class='form-error'>*Please check first name <br></span>
<span class='form-error'>*Please check last name <br></span>
<span class='form-error'>*Please check email <br></span>
";
$errorfirst=true;
$erroremail=true;
} else {
// Check if input characters are valid
if (!preg_match("/^[a-zA-Z]*$/", $first) || !preg_match("/^[a-zA-Z]*$/", $last)) {
echo "<span class='form-error'>*write properly</span>";
$errorfirst=true;
$errorlast=true;
} else {
//Check if email is valid
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "<span class='form-error'>*write a proper email</span>";
} else {
$sql = "SELECT * FROM name WHERE user_email='$email'";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0) {
echo "<span class='form-error'>This E-mail ID is already existed</span>";
} else {
//Hashing the password
$hashedPwd = password_hash($pwd, PASSWORD_DEFAULT);
// Insert the user into the database
$sql = "INSERT INTO name (id,user_first, user_last, user_email, user_uid, user_pwd) VALUES (NULL,'$first', '$last', '$email', '$uid', '$hashedPwd');";
mysqli_query($conn, $sql);
}
}
}
}
} else {
header("Location: ../signupform.php");
exit();
}
?>
<script type="text/javascript">
$('.first-input,.last-input,.email-input').removeClass('input-error');
var errorfirst="<?php echo '$errorfirst'; ?>";
var errorlast="<?php echo '$errorlast'; ?>";
var erroremail="<?php echo '$erroremail'; ?>";
if (errorfirst==true) {
$('.first-input').addClass('input-error');
}
if (errorlast==true) {
$('.last-input').addClass('input-error');
}
if (erroremail==true) {
$('.email-input').addClass('input-error');
}
if (erroremail==false && errorfirst==false && errorlast==false) {
$('.first-input,last-input,.email-input').val('');
}
</script>
It is not sending any value to the database. I used jQuery to validate form without refreshing but I think because of jQuery my form is not working
Here is my jQuery code
<script>
$(document).ready(function () {
$('.signup-Form').submit(function(event){
event.preventDefault();
var first=$(".first-input").val();
var last=$(".last-input").val();
var email=$(".email-input").val();
var college=$(".college-input").val();
var password=$(".password-input").val();
var submit=$(".signup-btn").val();
$(".form-message").load("includes/signup.inc.php", {
first:first,
last:last,
email:email,
college:college,
password:password,
submit:submit
})
});
});
</script>
And here is my HTML form
<form class="signup-Form" action="includes/signup.inc.php" method="post">
<div class="first-input">
<input type="text" name="first" placeholder="First Name">
</div>
<div class="last-input">
<input type="text" name="last" value="" placeholder="Last Name">
</div>
<div class="email-input">
<input type="text" name="email" value="" placeholder="E-mail">
</div>
<div class="college-input">
<input type="text" name="college" value="" placeholder="College Name">
</div>
<div class="password-input">
<input type="password" name="password" value="" placeholder="Password">
</div>
<p class="form-message"></p>
<div class="signup-btn">
<button type="submit" name="button">sign-up</button>
</div>
</form>
Help me over this issue and I also don't know about security in PHP forms so you can aslo suggest me some tips over that, I will really appreciate because I am want to be a professional back-end developer and now I am a newbie
Your jQuery uses $(".first-input").val(), but you have class="first-input" on the DIV, not the input.
Either move the class attribute to the inputs, or change the selector to $(".first-input input").val() (and similarly for all the other inputs).
You need to grab the input, not the container
<form class="signup-Form" action="includes/signup.inc.php" method="post">
<div class="first-input">
<input id="first-input" type="text" name="first" placeholder="First Name">
</div>
<div class="last-input">
<input id="last-input" type="text" name="last" value="" placeholder="Last Name">
</div>
<div class="email-input">
<input id="email-input" type="text" name="email" value="" placeholder="E-mail">
</div>
<div class="college-input">
<input id="college-input" type="text" name="college" value="" placeholder="College Name">
</div>
<div class="password-input">
<input id="password-input" type="password" name="password" value="" placeholder="Password">
</div>
<p class="form-message"></p>
<div class="signup-btn">
<button id="signup-btn" type="submit" name="button">sign-up</button>
</div>
</form>
<script>
$(document).ready(function () {
$('.signup-Form').submit(function(event){
event.preventDefault();
var first=$("#first-input").val();
var last=$("#last-input").val();
var email=$("#email-input").val();
var college=$("#college-input").val();
var password=$("#password-input").val();
var submit=$("#signup-btn").val();
$(".form-message").load("includes/signup.inc.php", {
first:first,
last:last,
email:email,
college:college,
password:password,
submit:submit
})
});
});
</script>

Can someone make an example of how to check if email and password exists in database with PDO? (FOR DUMMIES).

Heres is all relevant code. What I want to do is sent some parameters to a php file using ajax, and check if they are in db. If not echo and error message and if they are echo success message. I don't know how to retrieve all result from the database and compare them with the ones I input. Thank you.
AJAX
$( document ).ready(function() {
$("input[name=send_login]").click(function() {
var value_email_login = $("#email_login").val() ;
var value_password_login = $("#password_login").val() ;
if(value_email_login == '' && value_password_login == ''){
$(".info_message_login").show();
$(".info_message_login").html("Campos Vacios");
}else{
$.ajax({
type: 'POST',
url: 'php/login.php',
data: {email: value_email_login, password: value_password_login},
success: function(){
$(".info_message_login").show();
$(".info_message_login").text("Bienvenido...");
},
error: function(response){
$(".info_message_login").show();
$(".info_message_login").text(response.responseText);
},
});
}
});
});
FORM
<form class="" action="" method="post">
<div class="form-group">
<input class="form-control" type="text" name="email" id="email_login" placeholder="Email"/>
</div>
<div class="form-group">
<input class="form-control" type="password" name="password" id="password_login" placeholder="Password"/>
</div>
<div class="form-group">
<input class=" btn btn-default " type="button" name="send_login" value="Send"/>
</div>
<div class="form-group">
<input class=" btn btn-default " type="reset" name="reset_login" value="Reset"/>
</div>
<div class="info_message_login" style="display:none;">
</div>
</form>
PHP FILE
<?php
session_start();
require_once "db.php";
$email = trim($_POST['email']);
$password = trim($_POST['password']);
$sql_login = 'SELECT * FROM users WHERE email = :email AND password = :password';
$statement = $connection->prepare($sql_login);
$statement->bindValue(':email', $email);
$statement->bindValue(':password', $password);
$statement->execute()
$statement = $connection->prepare(<<<SQL
SELECT *
FROM users
WHERE email = :email
AND password = :password
SQL
);
$statement->execute(array(":email" => $email,
":password" => $password));
if($statement->fetch()) {
$_SESSION['login'] = 'ok';
}
I let you hash passwords with sha1 or whatever you want

Confused with name, id, onclick, onsubmit - what am i doing wrong in submitting data in db?

My code given below. Please help me correct the code. Iam confused with syntax. Also I do not know where exactly to put error message alert if there is any database issue and how to close the database. Please help
<form id="ContactForm" name="form1" method="post" onsubmit="submitdata()">
<div>
<div class="formwrap"><span>Your Name:</span><input name="fname" type="text" class="input" ></div>
<div class="formwrap"><span>Your E-mail:</span><input type="text" name="femail" class="input" ></div>
<div class="formwrap"><span>Your Mobile:</span><input type="text" name="fmobile" class="input" ></div>
<div class="formwrap"><span>Your City:</span><input type="text" name="fcity" class="input" ></div>
<div class="textarea_box"><span>Your Message:</span><textarea name="fmessage" cols="1" rows="1"></textarea></div>
<a class="button" onClick="document.getElementById('ContactForm').submit()"><span class="shadow"></span>Send</a>
<a class="button" onClick="document.getElementById('ContactForm').reset()"><span class="shadow"></span>Clear</a>
</div>
</form>
<?php
function submitdata(){
include "config/connection.php";
$fdname = $_POST['fname']);
$fdemail = $_POST['femail']);
$fdmobile = $_POST['fmobile']);
$fdcity = $_POST['fcity']);
$fdmessage = $_POST['fmessage']);
$sql="INSERT INTO users (name, email, mobile, city, message)
VALUES ('$fdname', '$fdemail', '$fdmobile', '$fdcity', '$fdmessage')";
}
?>
Thank you
I changed the action on your html form and created the php script that will handle and store your data into the database,take a look and do some further reading on prepared statements.
<form id="ContactForm" name="form1" action="insert.php" method="post">
<div>
<div class="formwrap"><span>Your Name:</span><input name="fname" type="text" class="input" ></div>
<div class="formwrap"><span>Your E-mail:</span><input type="text" name="femail" class="input" ></div>
<div class="formwrap"><span>Your Mobile:</span><input type="text" name="fmobile" class="input" ></div>
<div class="formwrap"><span>Your City:</span><input type="text" name="fcity" class="input" ></div>
<div class="textarea_box"><span>Your Message:</span><textarea name="fmessage" cols="1" rows="1"></textarea></div>
<a class="button" onClick="document.getElementById('ContactForm').submit()"><span class="shadow"></span>Send</a>
<a class="button" onClick="document.getElementById('ContactForm').reset()"><span class="shadow"></span>Clear</a>
</div>
</form>
insert.php
<?php
if($_POST){
$db = new mysqli("address","id","password","DBname");
if (mysqli_connect_errno())
{
echo "Connection Failed: " . mysqli_connect_errno();
exit();
}
$stmt = $db->prepare("INSERT INTO users (name, email, mobile, city, message) VALUES (?, ?, ?, ?, ?)");
$stmt -> bind_param('sssss', $fname, $femail, $fmobile, $fcity, $fmessage);
$fname = $_POST['fname'];
$femail = $_POST['femail'];
$fmobile = $_POST['fmobile'];
$fcity = $_POST['fcity'];
$fmessage = $_POST['fmessage'];
$stmt -> execute();
$stmt -> close();
$db -> close();
}
?>
You can use something like this (if you have jQuery included):
<script>
$(document).ready(function () {
$('form[name=form1]').submit(function () {
var fname = $('input[name=fname]').val();
var femail = $('input[name=femail]').val();
var fmobile = $('input[name=fmobile]').val();
var fcity = $('input[name=fcity]').val();
var fmessage = $('textarea[name=fmessage]').val();
$.post("/ajax/insert.php", {
'fname': fname,
'femail': femail,
'fmobile': fmobile,
'fcity': fcity,
'fmessage': fmessage
}, function (data) {
if (data == 1) {
alert("Success");
} else {
alert("Error");
}
});
});
});
</script>
Then make folder "ajax" in the root of website and make there a script called insert.php (if you want different name, edit line 9 in the js code). Content of the insert.php will be something like this:
<?php
include "config/connection.php";
$fdname = $_POST['fname'];
$fdemail = $_POST['femail'];
$fdmobile = $_POST['fmobile'];
$fdcity = $_POST['fcity'];
$fdmessage = $_POST['fmessage'];
$sql="INSERT INTO users (name, email, mobile, city, message)
VALUES ('$fdname', '$fdemail', '$fdmobile', '$fdcity', '$fdmessage')";
mysql_query($sql);
if(mysql_error()) {
echo 0;
} else {
echo 1;
}
?>
For onsubmit attribute JS function or codes is required not PHP function. But you provided a PHP function in onsubmit. I suggest you to use AJAX or action in form.
An Example for you
<form id="ContactForm" name="form1" >
<div>
<div class="formwrap"><span>Your Name:</span><input name="fname" type="text" class="input" ></div>
<div class="formwrap"><span>Your E-mail:</span><input type="text" name="femail" class="input" ></div>
<div class="formwrap"><span>Your Mobile:</span><input type="text" name="fmobile" class="input" ></div>
<div class="formwrap"><span>Your City:</span><input type="text" name="fcity" class="input" ></div>
<div class="textarea_box"><span>Your Message:</span><textarea name="fmessage" cols="1" rows="1"></textarea></div>
<a class="button" id="submit"><span class="shadow"></span>Send</a>
<a class="button" onClick="document.getElementById('ContactForm').reset()"><span class="shadow"></span>Clear</a>
</div>
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script>
$('#submit').click(function(){
$.ajax({
url: 'test.php',
data: $('#ContactForm').serialize(),
type: 'post',
success: function(data){
if(data == 'inserted'){
alert('Inserted');
}else{
console.log(data);
}
}
});
});
</script>
In test.php
include "config/connection.php";
$fdname = $_POST['fname'];
$fdemail = $_POST['femail'];
$fdmobile = $_POST['fmobile'];
$fdcity = $_POST['fcity'];
$fdmessage = $_POST['fmessage'];
$sql="INSERT INTO users (name, email, mobile, city, message)
VALUES ('$fdname', '$fdemail', '$fdmobile', '$fdcity', '$fdmessage')";
// if you use mysql connection
$result = mysql_query($sql);
if($result) {
echo 'inserted';
} else {
die(mysql_error());
}
You also fix some syntax error. Remove ) after each $_POST.

Categories