form validation through class - php

I am new to OOP. I want to use the values of class functions in a mySql query. But I am having difficulty retrieving the values. So maybe my method is not correct.
Below is my code and the result. As you can see, the echoed values are empty.
(If the attached code is not sufficient, then please let me know.)
Code:
if(isset($_POST['hidden']))
{
$validator = new FormValidator();
$fname =$validator->addValidation("fname","req","Please fill in First Name");
$email= $validator->addValidation("email","email","The input for Email should be a valid email value");
$lname= $validator->addValidation("lname","req","Please fill in Last Name");
$pass= $validator->addValidation("pass","req","Please fill in Password");
$con_pass= $validator->addValidation("confirmpass","req","Please fill in Confirm Password");
$sname= $validator->addValidation("sname","req","Please fill in Screen Name");
if($validator->ValidateForm())
{
echo $insert_query ="insert into registeration set fname = '".$fname."', lname = '".$lname."', email = '".$email."', pass = '".$pass."', cpass = '".$con_pass."', sname = '".$sname."' ";
mysql_query($insert_query);
Result:
insert into registeration set fname = '', lname = '', email = '', pass = '', cpass = '', sname = ''

Query you are using is more appropriate if you are updating an existing record try this
if($validator->ValidateForm())
{
$fname = $_POST['fname']; // name of your input field
$lname = $_POST['lname'];
$email = $_POST['email'];
$pass = $_POST['pass'];
$con_pass = $_POST['con_pass'];
$sname = $_POST['sname'];
$insert_query = mysql_query("INSERT INTO registeration (fname,lname,email,pass,cpass,sname)
VALUES ('$fname','$lname','$email','$pass','$con_pass','$sname')") or die(mysql_error());
}
( edited ) and reason for not working is because your variables are equal to the instance of methods you are calling you need to make them equal to the input fields.
Hope this can help you

Related

Login check with php MySQL and HTML

I am building a website's login page for an assignment. When I hash the password in the file that checks the users details it doesn't match with the stored hashed password in the database. The code always goes to the last else statement and relinks me to the login page with the wrong password sv equal to 1. If I don't hash the password, then copy and paste the hashed password from the database into the login form the login works. If anyone can help this would be greatly appreciated
ini_set('display_errors', 1);
ini_set('log_errors',1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
session_start();
$email = $_POST["email"];
$pass1 = $_POST["pass"];
$pass = hash('sha256', $pass1);
if(isset($_SESSION['user_type']))
{
unset($_SESSION['user_type']);
}
include("group_detail.php");
$query = "SELECT * from employee WHERE email = '$email' AND password = '$pass'";
$result_employee = $db->query($query);
$employee_row = mysqli_fetch_assoc($result_employee);
if(!empty($employee_row)){
$_SESSION['id'] = $employee_row['employee_ID'];
$_SESSION['name'] = $employee_row['name'];
$_SESSION['user_type'] = $employee_row['title'];
header('Location: homepage.html');
}else{
$query = "SELECT * from customer WHERE email = '$email' AND password = '$pass'";
$result_customer = $db->query($query);
$customer_row = mysqli_fetch_assoc($result_customer);
if(!empty($customer_row)){
$_SESSION['id'] = $customer_row['customer_ID'];
$_SESSION['name'] = $customer_row['name'];
$_SESSION['user_type'] = 'Customer';
$_SESSION['email'] = $customer_row['email'];
header('Location: homepage.html');
}
else{
$_SESSION['wrong_password'] = 1;
header('Location: login.php');
}
}
The registration code
<<?php
// this code checks all reuired fields are filled in appropriately
ini_set('display_errors', 1);
ini_set('log_errors',1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
session_start();
$nameErr = $phoneErr = $emailErr = $passwordErr = "";
$name = $address = $eircode = $email = $password = $phone = "";
$employee_ID = 0;
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
echo $nameErr;
if (empty($_POST["name"])) {
$nameErr = "Your name is required for registration";
} else {
$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and a space allowed";
}
}
if (empty($_POST["phone"])) {
$phoneErr = "Your phone number is required for registration";
} else {
$phone = test_input($_POST["phone"]);
}
if(empty($_POST['email']))
{
$emailErr = "Your Email is required for registration";
} else {
include ("group_detail.php");
$email_test = test_input($_POST["email"]);
$sql = "SELECT * from customer WHERE email = '$email_test'";
// Checks if another account uses this email
$result = $db->query($sql); // runs the query
$num_rows_3= mysqli_num_rows($result); // counts how many rows the query applies to
if($num_rows_3 == 0){
// Sets email value if no one else has used this email to sign up before
$email = test_input($_POST["email"]);
}
else{
// Lets the customer know this email is already in use
$emailErr = "Another account has previously been registered with this email. If this is you, you can login ";
}
}
if(empty($_POST['pass1']))
{
$passwordErr = "Password required";
} else {
$pass1 = $_POST['pass1'];
$pass2 = $_POST['pass2'];
if($pass1 == $pass2){
$pass = hash('sha256',$pass1);
// $pass = $pass1;
} else{
$passwordErr = "The passwords you enter must match";
}
}
if(empty($_POST['address']))
{
$address = "";
}else{
$address = test_input($_POST['address']);
}
if(empty($_POST['eircode']))
{
$eircode = "";
}else{
$eircode = test_input($_POST['eircode']);
}
if ($phoneErr == "" && $nameErr == "" && $passwordErr == "" && $emailErr == "")
{
// This code enters the data from the form into the customer table
include ("group_detail.php");
$q = "INSERT INTO customer(";
$q .= "name, phone, password, email, address, eircode";
$q .= ") VALUES (";
$q .= "'$name', '$phone', '$pass', '$email', '$address', '$eircode')";
$result = $db->query($q);
$sql = "SELECT customer_ID FROM customer ORDER BY customer_ID DESC LIMIT 1";
$result1 = $db->query($sql);
$row = mysqli_fetch_assoc($result1);
$_SESSION['customer'] = $row['customer_ID'];
header('Location: homepage.html');
}
}
?>
Solution
Your field is of the incorrect length. When you use the SHA256 hash function you get an output similar to:
ef92b778bafe771e89245b89ecbc08a44a4e166c06659911881f383d4473e94f // password123
If you're password field is only 15 characters then the saved value will be truncated:
ef92b778bafe771
However, during the comparison the full value from the logon script is used against the truncated version stored in the DB and therefore there is no match. Because, as you can see above, they aren't the same.
To fix you need to ALTER the table so that the field is at least varchar(64). Then new accounts will work as expected (note: old hashes still won't work - they need to be redone!)
Additional information
There are a few other issues with your code...
You shouldn't be putting variables directly into your code. Instead it is preferred to use a Prepared Statement with parametrised queries where you bind the variables later.
Which basically means in the query we use a place holder ? where we want a variable and then bind variables to the place holders later on
This is mainly to prevent SQL injection and protect you from incorrect input
It is best to use the PHP built in functions password_* to hash and verify passwords.
It's more secure than simply using hash
salts are auto-generated which protects you from things like rainbow tables
The default algorithm for password_hash requires a field length of 60+ characters
There's no need to store excess data in SESSION
The data is already stored in the DB so just fetch it as and when needed
It seems that you have one table for customers and another for employees
This isn't a good design there should be one table for users and then you can set flags for employee, customer, supplier etc.
Your test_input function carries out functions that are usually done on display not on save.
Below is a quick re-write that addresses some of the above (note: the below code is not complete it doesn't, for example, carry out all of the same validation - e.g. checking for illegal characters - it's just for illustrative purposes)
Register
<?php
ini_set('display_errors', true);
ini_set('log_errors', true);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
session_start();
$errors = [];
$name = $_POST["name"] ?? null;
$phone = $_POST["phone"] ?? null;
$email = $_POST['email'] ?? null;
$address = $_POST['address'] ?? null;
$eircode = $_POST['eircode'] ?? null;
$pass1 = $_POST['pass1'] ?? null;
$pass2 = $_POST['pass2'] ?? null;
// Check passwords are the same and assign hash to $pass
$pass = $pass1 === $pass2 ? password_hash($pass1, PASSWORD_DEFAULT) : null;
// Check the required fields are present and not empty
if (!$name || !$phone || !$email || !$pass) {
$errors[] = "Required fields are missing.";
}
// Check if the email address already exists in the DB
$checkEmailExistsSQL = "SELECT COUNT(*) as countEmails FROM user WHERE email = ?";
$checkEmailExistsQuery = $mysqli->prepare($checkEmailExistsSQL);
$checkEmailExistsQuery->bind_param("s", $email);
$checkEmailExistsQuery->execute();
$emailExists = $checkEmailExistsQuery->get_result()->fetch_assoc()["countEmails"];
if ($emailExists !== 0) {
$errors[] = "The email address already exists in the DB";
}
// Check if there were errors and output them; then exit the script
if (count($errors)) {
foreach($errors as $error) {
echo $error, PHP_EOL;
}
exit;
}
include("group_detail.php");
$insertSQL = "
INSERT INTO user
(name, phone, password, email, address, eircode)
VALUES
(?, ?, ?, ?, ?, ?)
";
$insertQuery = $mysqli->prepare($insertSQL);
$insertQuery->bind_param("ssssss", $name, $phone, $pass, $email, $address, $eircode);
$insertQuery->execute();
// Success the user is registered
Logon
<?php
ini_set('display_errors', true);
ini_set('log_errors', true);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
session_start();
$email = $_POST["email"] ?? null;
$pass = $_POST["pass"] ?? null;
// You can remove the old user id. But you don't need to
//
// There's no need to store excess data on the user in
// the SESSION super global; any data that you need
// access to can be retrieved from the DB at will.
// Copying data into SESSION only eats into memory.
unset($_SESSION["id"]);
// Check that something was submitted for email and password
if (!$email || !$pass) {
echo "Error: all fields need to be completed";
exit;
}
include("group_detail.php");
$sql = "SELECT id, password FROM user WHERE email = ?";
$query = $mysqli->prepare($sql);
$query->bind_param("s", $email);
$query->execute();
// Check to see if the email address is registered.
// Then check to see if the password is a match.
if (
!($user = $query->get_result()->fetch_assoc())
|| !password_verify($pass, $user["password"])
) {
echo "Error: the email address or password isn't correct";
exit;
}
// Success the user is logged on
//
$_SESSION["id"] = $user["id"];

how do I create an SQL and PHP IF statement with else

I have created a if statement that is to check if a username is stored on the SQL database, I am not sure why when it checks the database it always finds that there is a username already inserted even when the database can be empty.
I have tried various variations of an if statement and I am not having much luck.
<?php
if(isset($_POST['save'])){
include 'includes/config.php';
$fname = $_POST['fname'];
$pass = $_POST['pass'];
$gender = $_POST['gender'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$location = $_POST['location'];
$check = "SELECT email FROM client WHERE email = '$email'";
$res_e = mysqli_query($db, $check);
if (mysqli_num_rows($res_e) == 0) {
echo "<script type = \"text/javascript\">
alert(\"Sorry... username already taken.\");
window.location = (\"signup.php\")
</script>";
} else {
$qry = "INSERT INTO `client`
VALUES('NULL','$fname','$email','$pass','$phone','$location','$gender',
'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL')";
$result = $conn->query($qry);
echo "<script type = \"text/javascript\">
alert(\"Successfully Registered. Proceed to Login.\");
window.location = (\"account.php\")
</script>";
}
}
I just need it to check if the username (email address) is stored and return that the username is already taken or if not already taken to insert the data into the database.
your're displaying the error if the email is not used (there's no user with this email)
if (mysqli_num_rows($res_e) == 0) {
Thanks for the comments, I noticed that I had a line of code missing:
$rws = $res_e->fetch_assoc();
And I changed the if statement to:
if ($rws == FALSE )
This has resolved my question.
Thanks again.

Difficulty passing variables from a two page sign up

I have two pages of form for the sign up process. Both forms feed into two different tables. users and user_profile. I am looking into using $_SESSIONS to pass a unique attribute from the first page to the second so that that there will be a relationship for each user on both tables. The ID column is incremental so i decided to use the username column because it is unique. Now i am having difficulty passing the username from the first page unto the second page so that i can add it to the insert statement for the sql. My code on the first page is as follows
<?php
session_start();
$_SESSION['message'] = '';
$_SESSION['var_user'] = 'username';
....
username is the name of the field from the formand on the second page, i have
<?php
session_start();
$_SESSION['message'] = '';
$username = $_SESSION['var_user'];
$mysqli = new mysqli("localhost", "root", "", "webdev");
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$houseno = ($_POST['str_number']);
$street =($_POST['str_name']);
$city = ($_POST['city']);
$county = ($_POST['county']);
$postcode = ($_POST['pst_code']);
$skills = ($_POST['skills']);
$_username = ($_POST[$username]);
$sql = ("INSERT INTO users_profile (house_no, street_name, city, county,
postcode, about_me, username) VALUES ('$houseno', '$street', '$city',
'$county', '$postcode', '$skills', '$_username')");
if ($mysqli->query($sql) === true){
$_SESSION['message'] = "Registration succesful! Added $username to the database!";
header("location: index.html");
} else{
$_SESSION['message'] = 'Registration Unsuccessful, Please login and update your information';
}
}
I have tried everything from using hidden input in the form. Doesn't seem to be working. Any help will be appreciated.
You're using $username as an key on the second page:
$username = $_SESSION['var_user'];
...
$_username = ($_POST[$username]);
Instead you should simply define it on the first page:
$_SESSION['var_user'] = $_POST['var_user']
And use it on the second page:
$username = $_SESSION['var_user'];

MySQL PHP Matching User ID's when creating a "USER"

I am coding a "social media site" for a class project, and I am having trouble in one section.
When first registering an account, the user must enter a username and password, and click a submit button. PHP code checks the inputs to make sure they're all valid and that there will not be any duplicates, and if everything passes, it adds in the username and password into a SQL table called "users". Users has 3 columns: username, password, and userID. userID is the primary key.
Once that process is completed, we redirect to a separate page, where the user can enter more personal information, such as first and last name, city, country, etc. This table, called "userInfo" has the columns: firstName, lastName, emailAddress, address, city, country, and userID. userID, once again, is the primary key.
What I'm trying to figure out is how to match the two user ID's in an insert statement. I have a form that gathers all the required information, but I am not sure how to set up the SQL query to make sure that users.userID matches userInfo.userID.
Here's my PHP for users (initial registration)
<?php
session_start();
require_once('dbConnect.php');
$error = "false";
$errorMessage = "";
if(isset($_POST['submit'])){
// Get inputs
$username = $_POST['user'];
$password = $_POST['password'];
// Clean inputs and encrypt password
$username = mysqli_real_escape_string($conn, $username);
$password = mysqli_real_escape_string($conn, $password);
$password = md5($password);
// Check username not empty
if (empty($username)) {
$error = "true";
$errorMessage = "Please enter a value for your username";
}
// Check username does not already exist
$checkUserQuery = "SELECT username FROM users WHERE username = '$username'";
$checkResult = $conn->query($checkUserQuery);
if($checkResult->num_rows > 0) {
$error = "true";
$errorMessage = "This username already exists";
}
// Username does not exist, add to database
else {
$insertUserQuery = "INSERT INTO users (username, password) VALUES('$username', '$password')";
$insertResult = $conn->query($insertUserQuery);
$_SESSION['username'] = $username;
header("Location: userInfo.php");
}
}
?>
Here's my PHP code so far for userInfo:
<?php
session_start();
require_once('dbConnect.php');
$error = "false";
$errorMessage = "";
$username = $_SESSION['username'];
if(isset($_POST['submit'])){
// Get inputs
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$emailAddress = "fakeEmailAddress#fakeyfakefake.com";
$address = $_POST['address'];
$city = $_POST['city'];
$country = $_POST['country'];
// Clean inputs
$firstName = mysqli_real_escape_string($conn, $firstName);
$lastName = mysqli_real_escape_string($conn, $lastName);
$address = mysqli_real_escape_string($conn, $address);
$city = mysqli_real_escape_string($conn, $city);
$country = mysqli_real_escape_string($conn, $country);
// Validate Inputs (Only validating first and last name, location entries are not required)
if(empty($firstName) || empty($lastName)) {
$error = "true";
$errorMessage = "Please enter your first AND last name";
}
else {
}
}
?>
Apologies if this is super messy. Databases are NOT my strong suit lol.
Many thanks to anyone who can help!
You'll want to get the mysqli_insert_id for your insert into the users table and pass that along (potentially via your $_SESSION) for creation in userInfo.

Php register form with mysql

I have made a register form with php and mysql. It works only if it is introduced diffrent name of user each time. How can i rezolve that? because sometimes i want to insert the same name in the database.
My code:
require('connect.php');
if (isset($_POST['adresa'])) {
$username = $_POST['username'];
$email = $_POST['email'];
$adresa = $_POST['adresa'];
$judet = $_POST['judet'];
$telefon = $_POST['telefon'];
$localitate = $_POST['localitate'];
$bon = $_POST['bon'];
$date = $_POST['date'];
$premiu = $_POST['premiu'];
$query = "INSERT INTO user (username, adresa, email,judet,telefon,localitate,bon,date,premiu,acord) VALUES ('$username', '$adresa', '$email','$judet','$telefon','$localitate','$bon','$date','$premiu','$acord')";
$result = mysql_query($query);
}
Use for check user name existence
<?php
require('connect.php');
if (isset($_POST['adresa'])) {
$username = $_POST['username'];
$email = $_POST['email'];
$adresa = $_POST['adresa'];
$judet = $_POST['judet'];
$telefon = $_POST['telefon'];
$localitate = $_POST['localitate'];
$bon = $_POST['bon'];
$date = $_POST['date'];
$premiu = $_POST['premiu'];
$chk_query = mysql_query("Select (username) from user where username=$username");
$num = mysql_num_rows($chk_query);
if($num < 1)
{
$query = "INSERT INTO user (username, adresa, email,judet,telefon,localitate,bon,date,premiu,acord) VALUES ('$username', '$adresa', '$email','$judet','$telefon','$localitate','$bon','$date','$premiu','$acord')";
$result = mysql_query($query);
}
else { echo "User name exist"; }
}
?>
If you can't insert multiple users with the same name to the database then the username field must have been flagged as UNIQUE at table declaration.
To remove this restriction use DROP INDEX
Note that, if the username field is a primary key you will need to drop the primary key and introduce another, a BIGINT for example (Best option).
IMPORTANT : mysql_ functions are deprecated and you should stop using them. Use mysqli_ or PDO instead

Categories