String data conversion: Inserting data from Spinner using mysql - php

I am trying to add data into MySQL database through spinner that has several options to choose. I do not know how to state value from spinner into MySQL code. The error occurs on the 39th line, which first line of Inserting Into database using MySQL code. I look forward to hearing from you soon.
<?php
include 'db.php';
$user_type = ['user_type'];
$first = $_POST['first'];
$last = $_POST['last'];
$email = $_POST['email'];
$username = $_POST['username'];
$password = $_POST['password'];
$phone = $_POST['phone'];
if(/*$user_type == '' ||*/ $first == '' || $last == '' || $email == '' || $username == '' || $password == '' || $phone == '')
{
echo 'Please, fill all fields';
} else{
$sql = "SELECT * FROM users WHERE user_username='$username'";
$check = mysqli_fetch_array(mysqli_query($conn,$sql));
if(isset($check))
{
echo 'Username already exist. Please, use another one.';
}else{
$hashedPWD = password_hash($password , PASSWORD_DEFAULT); //hash password
$sql = "INSERT INTO users (user_type, user_first, user_last, user_email, user_username, user_pwd, user_phonenumber) VALUES('$user_type','$first','$last','$email','$username','$hashedPWD','$phone')";
if(mysqli_query($conn,$sql))
{
echo 'Successfully registered';
} else{
echo 'Oops! Please try again!';
}
}
mysqli_close($conn);
}

Related

Wrong Username/Password Message though the record exists in the database

I just started off with PHP and attempted to make a simple login and sign-up page. The sign-up module works perfectly with the records being successfully being inserted into the database. But, whenever I try to log in, it always throws me a wrong password/username combination.
I am really new to web development so I am not looking for advice on SQL injections and other security-related issues. Could someone just tell me how I could make this work using PHP and MySQL only.
I am using the XAMPP server with phpMyAdmin.
Here is my Config.php file which I use to validate the data I accept through the forms.
<?php
session_start();
//variable declaration
$email = "";
$name = "";
$batch = "";
$password = "";
$errors = array();
$_SESSION['success'] = "";
//connect to database
$conn = mysqli_connect('localhost', 'root', '', 'timetable');
//Register User
if(isset($_POST['reg_user']))
{
$email = mysqli_real_escape_string($conn, $_POST['email']);
$name = mysqli_real_escape_string($conn, $_POST['name']);
$batch = mysqli_real_escape_string($conn, $_POST['batch']);
$password_1 = mysqli_real_escape_string($conn, $_POST['password_1']);
$password_2 = mysqli_real_escape_string($conn, $_POST['password_2']);
//form validation
if($batch != 2016 || $batch != 2017 || batch != 2018 || batch != 2019)
{
array_push($errors, "Batch should be one of 2016/2017/2018/2019.");
}
if($password_1 != $password_2)
{
array_push($errors, "The two passwords do not match.");
}
if(count($errors) == 0)
{
$password = hash('sha512', $password);
$query = "INSERT INTO chairperson(email, name, batch, password)
VALUES('$email', '$name', '$batch', '$password')";
mysqli_query($conn, $query);
$_SESSION['email'] = $email;
$_SESSION['success'] = "You are now logged in.";
header('location: index.php');
}
}
//Login user
if(isset($_POST['login_user']))
{
$email = mysqli_real_escape_string($conn, $_POST['email']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
if(count($errors) == 0)
{
$password = hash('sha512', $password);
$query = "SELECT * FROM chairperson WHERE email='$email' AND password='$password'";
$results = mysqli_query($conn, $query);
if(mysqli_num_rows($results) == 1)
{
$_SESSION['success'] = "You are now logged in.";
$_SESSION['email'] = $email;
header('location: index.php');
}
else
{
array_push($errors, "Wrong username/password combination.");
}
}
}
?>
<?php
session_start();
//variable declaration
$email = "";
$name = "";
$batch = "";
$password = "";
$errors = array();
$_SESSION['success'] = "";
//connect to database
$conn = mysqli_connect('localhost', 'root', '', 'timetable');
//Register User
if(isset($_POST['reg_user']))
{
$email = mysqli_real_escape_string($conn, $_POST['email']);
$name = mysqli_real_escape_string($conn, $_POST['name']);
$batch = mysqli_real_escape_string($conn, $_POST['batch']);
$password_1 = mysqli_real_escape_string($conn, $_POST['password_1']);
$password_2 = mysqli_real_escape_string($conn, $_POST['password_2']);
//form validation
if(($batch != 2016) && ($batch != 2017) && ($batch != 2018) && ($batch != 2019))
{
array_push($errors, "Batch should be one of 2016/2017/2018/2019.");
}
if($password_1 != $password_2)
{
array_push($errors, "The two passwords do not match.");
}
if(count($errors) == 0)
{
$password = password_hash($password,PASSWORD_BCRYPT);
$query = "INSERT INTO chairperson(email, name, batch, password)
VALUES('$email', '$name', '$batch', '$password')";
mysqli_query($conn, $query);
$_SESSION['email'] = $email;
$_SESSION['success'] = "You are now logged in.";
header('location: index.php');
}
}
//Login user
if(isset($_POST['login_user']))
{
$email = mysqli_real_escape_string($conn, $_POST['email']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
if(count($errors) == 0)
{
$query = "SELECT * FROM chairperson WHERE email='$email' ";
$results = mysqli_query($conn, $query);
if(mysqli_num_rows($results) == 1)
{
$row=mysqli_fetch_assoc($results);
if(password_verify($password, $row['password']))
{
$_SESSION['success'] = "You are now logged in.";
$_SESSION['email'] = $email;
header('location: index.php');
}
else
{
array_push($errors, "Wrong username/password combination.");
}
}
else
{
array_push($errors, "Wrong username/password combination.");
}
}
}
?>

Optimised PHP code for multiple input check

There is a PHP update form where a user can update his records. The below-mentioned code looks redundant to me. How can I optimize this PHP code? Also, I have the admins username and email in a different table and the admin detail columns (such as first name, last name, gender, dob) in a different table. What will be the best way to check if username and email both have been updated or if any one of them and update it in the database accordingly.
Below is my source code:
if(isset($_POST['btnClick']) {
$f_name = NULL;
$l_name = NULL;
$username = NULL;
$email = NULL;
$gender = NULL;
$dob = NULL;
$f_name = filter_input(INPUT_POST, "f_name", FILTER_SANITIZE_STRING);
$l_name = filter_input(INPUT_POST, "l_name", FILTER_SANITIZE_STRING);
$username = filter_input(INPUT_POST, "username", FILTER_SANITIZE_STRING);
$email = filter_input(INPUT_POST, "email", FILTER_VALIDATE_EMAIL);
$gender = filter_input(INPUT_POST, "gender", FILTER_VALIDATE_STRING);
$dob = filter_input(INPUT_POST, "dob", FILTER_VALIDATE_STRING);
try {
if(isset($username) && $username != $_SESSION['username']) {
$sqlUpdate = "UPDATE admins SET username=:username WHERE admin_id=:admin_id";
/*Update code here...*/
echo "Username changed value inputted";
}
else if(isset($email) && $email != $_SESSION['email']) {
$sqlUpdate = "UPDATE admins SET username=:username WHERE admin_id=:admin_id";
/*Update code here...*/
echo "email change value inputted";
}
else if(isset($username) && isset($email)) {
/*Update both records */
}
You can do something like this:
<?php
try {
if (isset($username) && $username != $_SESSION['username']) {
$fieldsToUpdate[] = 'username=:username';
$updatedFields[] = 'Username';
}
if (isset($email) && $email != $_SESSION['email']) {
$fieldsToUpdate[] = 'email=:email';
$updatedFields[] = 'Email';
}
if (isset($fieldsToUpdate) && count($fieldsToUpdate) > 0) {
$sqlUpdate = "UPDATE admins SET " . implode($fieldsToUpdate, ', ') . " WHERE admin_id=:admin_id";
/*Update code here...*/
$finalMessage = 'Fields: ' . implode($updatedFields, ', ') . ' have been updated.';
}
}
PS: This is an example code that how can you optimize your code with PHP arrays and implode() function to run single query to update single or multiple fields.

Hashed password not coming out to what it should be (PHP)

So I'm trying to make a fairly simple login system, but for some reason the hashed password that is being sent to my database is not hashing correctly. I checked my database and the stored password is not what the sha256 hashed with the generated salt appended is not what it's supposed to be. Here's my code for generating the hash that's being uploaded to the database:
<?php
include "connection.php";
//Check Connection
if ($connect->connect_error) {
echo "Failed to connect to server: " . mysqli_connect_error();
}
//Reset all Checks
$username_exists = NULL;
$email_valid = NULL;
$passwords_match = NULL;
$password_acceptable = NULL;
$password_long_enough = NULL;
$password = NULL;
//Prepare Statements
//Check for Username Existing Statement
$check_username_match = $connect->stmt_init();
$sql_check_username = "SELECT id FROM $tablename WHERE username=?";
$check_username_match->prepare($sql_check_username);
$check_username_match->bind_param("s", $username);
//Insert Into Table Statement
$register_query = $connect->stmt_init();
$sql_register = "INSERT INTO $tablename (username, email, password, token, active, level) VALUES (?, ?, ?, ?, ?, ?)";
$register_query->prepare($sql_register);
$register_query->bind_param("sssssi", $username, $email, $hashedpassword, $token, $activated, $level);
//Execute When Form Submitted
if($_SERVER["REQUEST_METHOD"] == "POST") {
$username = mysqli_escape_string($connect, $_POST['username']);
$email = mysqli_escape_string($connect, $_POST['email']);
$password = $_POST['password'];
$confirm_password = $_POST['confirm_password'];
//Check if Username Exists
$check_username_match->execute();
$check_username_match->store_result();
$numrows = $check_username_match->num_rows;
if ($numrows==0){
$username_exists = false;
} else {
$username_exists=true;
}
//Check if Passwords Match
if ($password==$confirm_password){
$passwords_match = true;
} else {
$passwords_match = false;
}
//Check if Email Address is Valid
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
$email_valid = true;
} else {
$email_valid = false;
}
//Check if Passwords Contains Special Characters
$uppercase = preg_match('#[A-Z]#', $password);
$lowercase = preg_match('#[a-z]#', $password);
$number = preg_match('#[0-9]#', $password);
//Check if Password is Long Enough
$password_length = strlen($password);
if ($password_length>8){
$password_long_enough = true;
} else {
$password_long_enough = false;
}
//Validate Password
if(!$uppercase || !$lowercase || !$number || !$password_long_enough || $password = '') {
$password_acceptable = false;
} else {
$password_acceptable = true;
}
//Register if all Validations Met
if(!$username_exists && $email_valid && $passwords_match && $password_acceptable){
//$salt = dechex(mt_rand(0, 2147483647)) . dechex(mt_rand(0, 2147483647));
$token = dechex(mt_rand(0, 2147483647)) . dechex(mt_rand(0, 2147483647));
$activated="No";
$level = 0;
$hashedpassword = password_hash($password, PASSWORD_DEFAULT);
$register_query->execute();
$message = "Hello, welcome to the site.\r\n\r\nPlease click on the following link to activate your account:\r\nlocalhost/login_system/activate.php?token=".$token;
mail($email, 'Please Activate Your Account', $message);
header("Location: login.php");
}
}
?>
UPDATE: I changed my above code to reflect the changes I made with password_hash. However, the problem still persists.
This is my login php:
<?php
include("connection.php");
session_start();
//Reset Variables
$message = '';
$location = "/login_system/index.php"; //default location to redirect after logging in
$username = '';
$password = '';
//Check to see if user is newly activated; if he is display a welcome message.
if(isset($_GET['activated'])){
if($_GET['activated'] == "true"){
$message = "Thank you for verifying your account. Please login to continue.";
}
}
//Check to see if user is coming from another page; if he is then store that page location to redirect to after logging in.
if(isset($_GET['location'])) {
$location = htmlspecialchars($_GET['location']);
}
echo $location;
//Prepare login check statement
$check_login = $connect->stmt_init();
$sql = "SELECT id, password FROM $tablename WHERE username=?";
$check_login->prepare($sql);
$check_login->bind_param("s", $username);
//Execute Login Check
if($_SERVER["REQUEST_METHOD"] == "POST") {
$username = mysqli_escape_string($connect, $_POST['username']);
$password = $_POST['password'];
$check_login->execute();
$check_login->store_result();
$numrows = $check_login->num_rows;
$check_login->bind_result($id, $match);
$check_login->fetch();
if ($numrows==1 && password_verify($password, $match)) {
$_SESSION['login_user'] = $id;
$goto = "localhost".$location;
header("location: $goto");
$message = "Success!";
} else {
$message="Username or password is not valid."."<br>".$match."<br>";
}
}
$connect->close();
?>
You should just feed the password you want to hash into PHP's password_hash();function. Like so...
$password = $_POST['password'];
$options = [
'cost' => 12,
];
echo password_hash($password, PASSWORD_BCRYPT, $options);
Then when you want to check if the password exists in the database use password_verify(); Like so...
$password = PASSWORD_HERE;
$stored_hash = HASH_HERE;
if (password_verify($password, $stored_hash)) {
echo 'Password is valid!';
} else {
echo 'Invalid password.';
}

PHP Login System Error Not appearing on page

I'm using notepad++ and Godaddy's phpMyAdmin to host the server. The file does not display anything when posted and whenever I put it in a PHP code checker it tells me this:
Error: There is 1 more opening parenthesis '(' found This count is unaware if parenthesis are inside of a string)
and
Error: There is 1 more opening curly braces '{' found
This count is unaware if curly braces are inside of a string
Any help would be much appreciated.`
//Declaring them as variables
$username = $_POST["username"];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$pass1 = $_POST['pass1'];
$pass2 = $_POST['pass2'];
//error handling
if((!$username) || (!$fname) || ($lname) || ($email) || ($pass1) || ($pass2))
{
$message = "please insert all fields in theform below!";
}
else
{
if($pass1 != $pass2)
{
$message = "Passwords do not match!"
}
}
else
//gathering the data
{
$username = preg_replace("#[^0-9a-z]#i","",$username);
$fname = preg_replace("#[^0-9a-z]#i","",$fname);
$lname = preg_replace("#[^0-9a-z]#i","",$lname);
$pass1 = sha1(#pass1);
$email = mysql_real_escape_string($email);
//check for dublicates
$user_query = mysql_query("SELECT username FROM members WHERE username ='$username' LIMIT 1") or die("Could not check username");
$count_username = mysql_num_rows($user_query);
$user_query = mysql_query("SELECT email FROM members WHERE username ='$email' LIMIT 1") or die("Could not check email");
$count_email = mysql_num_rows($email_query);
if($count_username > 0)
{
$message = "Your username is alread in use";
}
else if($count_email > 0)
{
$message = " Your email is alread in use";
}
else
//insert the memebers to database
{
$ip_address = $_SERVER['REMOTE_ADDR'];
$query = mysql_query("INSERT INTO members(username, firstname, lastname,email,password,ip_adress,sign_up_date)VALUES('$username','$fname','$lname','$email', '$pass1','$ip_address',now()")or die("could not insert");
$member_id = mysql_insert_id();
mkdir(,"users/$member_id",0755);
$message = "You have now been registered";
}
}
The issue is that your else statement was misplaced. I moved it after the if statement where you check that the passwords match.
//Declaring them as variables
$username = $_POST["username"];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$pass1 = $_POST['pass1'];
$pass2 = $_POST['pass2'];
//error handling
if((!$username) || (!$fname) || ($lname) || ($email) || ($pass1) || ($pass2))
{
$message = "please insert all fields in theform below!";
}
else
{
if($pass1 != $pass2)
{
$message = "Passwords do not match!"
}
else
{
//All required fields are filled
//Paswords match
//gathering the data
$username = preg_replace("#[^0-9a-z]#i","",$username);
$fname = preg_replace("#[^0-9a-z]#i","",$fname);
$lname = preg_replace("#[^0-9a-z]#i","",$lname);
$pass1 = sha1(#pass1);
$email = mysql_real_escape_string($email);
//check for dublicates
$user_query = mysql_query("SELECT username FROM members WHERE username ='$username' LIMIT 1") or die("Could not check username");
$count_username = mysql_num_rows($user_query);
$user_query = mysql_query("SELECT email FROM members WHERE username ='$email' LIMIT 1") or die("Could not check email");
$count_email = mysql_num_rows($email_query);
if($count_username > 0)
{
$message = "Your username is alread in use";
}
else if($count_email > 0)
{
$message = " Your email is alread in use";
}
else
//insert the memebers to database
{
$ip_address = $_SERVER['REMOTE_ADDR'];
$query = mysql_query("INSERT INTO members(username, firstname, lastname,email,password,ip_adress,sign_up_date)VALUES('$username','$fname','$lname','$email', '$pass1','$ip_address',now()")or die("could not insert");
$member_id = mysql_insert_id();
mkdir(,"users/$member_id",0755);
$message = "You have now been registered";
}
}
}

How do I check database for a value that already exists?

I am currently building a signup script for my website. I new to the whole PHP-mySQL interaction bit. Anyway, this is the code I've gotten so far. The problem is that I had added some more code to check if the username already exists in the database, after the form submits it kicks to store.viddir.com/join/signup.php rather than store.viddir.com/login, like I had it. Any pros that can help a novice out? Many thanks
<?php
$submitted = $_POST["submitted"];
if($submitted == 'yes') {
$firstName = $_POST["firstName"];
$lastName = $_POST["lastName"];
$userName = $_POST["userName"];
$password = $_POST["password"];
$confirmPassword = $_POST["confirmPassword"];
$eMail = $_POST["eMail"];
// Kill script if input fields are blank
if ($firstName == '' or $lastName == '' or $userName == '' or $password == '' or $confirmPassword == '' or $eMail == '')
{
die();
}
// Check if passwords match
if ($password != $confirmPassword)
{
die();
}
// Check if password is appropriat length
$passwordLength = strlen($password);
if ($passwordLength < 7 or $passwordLength >30) {
die();
}
/////////////////////////
// Connect to database //
/////////////////////////
$sqlserver = "localhost";
$sqluser = "XXXX";
$sqlpassword = "XXXXXX";
mysql_connect($sqlserver, $sqluser, $sqlpassword) or die(mysql_error());
mysql_select_db("store");
// Check database if username already exists
$newUserName = $userName;
$checkUserName = mysql_query("SELECT userName FROM userInfo WHERE userName = '$newUserName'");
if ($checkUserName) {
die();
}
//////////////////////////
// Insert into database //
//////////////////////////
// Signup time in Unix Epoch
$time = time();
// Human readable date
$date = date("F jS, Y g:i:s A");
$sql = "INSERT into userInfo (firstName, lastName, userName, password, eMail, time, date) VALUES ('$firstName', '$lastName', '$userName', '$password', '$eMail', '$time', '$date')";
//$sqlserver = "localhost";
//$sqluser = "XXXX";
//$sqlpassword = "XXXXXX";
//mysql_connect($sqlserver, $sqluser, $sqlpassword) or die(mysql_error());
//mysql_select_db("store");
mysql_query($sql) or die(mysql_error());
mysql_close();
header("Location: http://store.viddir.com/login");
exit;
}
?>
See mysql_num_rows. You should also look into using PDO or MySQLi
http://php.net/manual/en/function.mysql-num-rows.php
if (mysql_num_rows($query) > 0) {
echo "user already exists";
}
You should do a count in the mysql query and then check if the result is not equal to 0.
Example:
// Check database if username already exists
$newUserName = $userName;
$checkUserName = mysql_query("SELECT COUNT(userName) FROM userInfo WHERE userName = '$newUserName'");
if ( mysql_result($checkUserName, 0, 0) != 0 ) {
die();
}

Categories