Insert into not creating new row - php

I've been trying to mess around with a registration system. However when I try to insert the information into the database. no new row is generated. I'm not getting any errors, and my code seems legitimate. Is there something that I don't know about INSERT INTO?
$username = $_POST['regusername'];
$email = $_POST['regemail'];
$password = $_POST['regpassword'];
$cpassword = $_POST['regpasswordcon'];
$firstname = $_POST['regfirstname'];
$lastname = $_POST['reglastname'];
//check username for weird symbols
if (preg_match('/[\'^£$%&*()}{##~?><>,|=_+¬-]/', $username)){
// one or more of the 'special characters' found in string
//header("Location: /register.php");
echo "Your username should only contain letters and numbers";
exit;
}
//check if username is taken
$check = $con->prepare("SELECT * FROM accounts WHERE username=:user");
$check->bindParam(':user',$username);
$check->execute();
$result = $check->fetch(PDO::FETCH_ASSOC);
if(!empty($result)){
//header("Location: /register-page.php"); //direct browser back to sign in
echo "User is already taken";
exit;
}else{ //otherwise proceed to register new user
//Hashing of password
$hpassword = password_hash($password, PASSWORD_DEFAULT);
//Prepared statements for SQL injection prevention
$query = $con->prepare("INSERT INTO accounts (username, password, email, firstname, lastname) VALUES (:name,:hpassword,:email,:fname,:lname) ");
//bind parameters
$query->bindParam(':name',$username);
$query->bindParam(':hpassword',$hpassword);
$query->bindParam(':email',$email);
$query->bindParam(':fname',$firstname);
$query->bindParam(':lname',$lastname);
$query->execute();
}

Related

How to verify password whith 2 different forms?

I have 2 forms : one for Registration and one for Login ([not on the same page, one is a modal][1])
(That's why I did 2 issets at the beginning)
The Registration one is working.
However the Login doesn't work because a User can log in with any password.
I want to verify username/email and of course password. How can I do it ?
Thank you!
Here is my code :
// REGISTRATION
if (isset($_POST['reg_user']) || isset($_POST['login_user'])) {
$username = mysqli_real_escape_string($db, $_POST['name']);
$email = mysqli_real_escape_string($db, $_POST['email']);
$password = mysqli_real_escape_string($db, $_POST['password']);
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
$query = "SELECT * FROM utilisateur WHERE pseudoUtil='$username' OR mailUtil='$email'";
$results = mysqli_query($db, $query);
if(mysqli_num_rows($results) == 1){
$_SESSION['message'] = "User already exists !";
}
else{
mysqli_query($db, "INSERT INTO utilisateur (pseudoUtil, mailUtil, pwdUtil) VALUES ('$username', '$email', '$hashed_password')");
$_SESSION['message'] = "Registration complete :)";
}
// LOGIN
if (isset($_POST['login_user'])) {
$query2 = "SELECT $hashed_password FROM utilisateur WHERE pseudoUtil='$username' OR mailUtil='$email'";
$results2 = mysqli_query($db, $query2);
if(mysqli_num_rows($results2) == 1){
$_SESSION['username'] = $username;
header('location: index.php');
}
else{
}
}
}
else{
}
[1]: https://i.stack.imgur.com/fCdAV.png
registration needs to create the password hash and save it to the database, log in needs to pull the hash from the database and compare to the password
both of these tasks should be complete isolated from each other
this means your code should look more like this
note this is an example only not tested as working
POST /register body: username=someone#some.where&password=123456789
function Register(){
$stmt = $mysqli->prepare("SELECT count * as count FROM users WHERE email=?");
$stmt->bind_param("s", $_POST["username"]);
$stmt->execute();
$result = $stmt->get_result();
if($result->fetch_array(MYSQLI_ASSOC)["count"]>0)
{
return "User already exists"
}
else
{
$hash = password_hash($_POST["password"],PASSWORD_DEFAULT);
$stmt = $mysqli->prepare("INSERT INTO users (username, hash) values (?,?)");
$stmt->bind_param("ss", $_POST["username"], $hash);
$stmt->execute();
$result = $stmt->get_result();
//either return success or set up as a successful login and perform login action
}
}
POST /login body: username=someone#some.where&password=123456789
function Login(){
$stmt = $mysqli->prepare("SELECT hash FROM users WHERE email=?");
$stmt->bind_param("s", $_POST["username"]);
$stmt->execute();
$result = $stmt->get_result();
if(password_verify($_POST["password"], $result->fetch_array(MYSQLI_ASSOC)["hash"]))
{
//do successful login
}
else
{
//log in failed
}
}

Login page keeps showing error PHP and MySQL

I am having issues getting some simple (or it seems simple) coding to cooperate. I've tried stripping it completely and typing everything out. Here is the code:
<?php
session_start();
if(isset($_POST['login'])) {
$username = trim($_POST['username']);
$password = md5(trim($_POST['password']));
include('includes/admin.php');
$sql = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$result = mysqli_query($con, $sql);
if(mysqli_num_rows($result) == 0) {
echo '<p>Incorrect login.<br>Return to Login Page</p>';
} else {
$_SESSION['user'] = $username;
echo '<p>Login successful.<br>Go to Admin Page</p>';
}
}
?>
The goal is to have it redirect to the login page if unsuccessful and to redirect to another admin page if successful. I keep getting the "Incorrect Login" error, even when I type in the correct username and password.
Side Note: I know to redirect, I need to use header('Location: link.php'), it is not included for testing purposes.
If you didn't save your password as MD5 hash in your database you will never match it, cause in the line above you hash the password via MD5 before using in the query.
MD5 isn't secure! Use the PHP internal functions (password_hash(), password_verify()) to create and check passwords!
Use prepared statements!
Example code:
<?php
// Save a new user password in DB
$username = 'Max User';
$password = 'My_Secr3t_Pa5sw0rd';
$passwordHash = password_hash($password, PASSWORD_BCRYPT);
$stmt = $mysqli->prepare("INSERT INTO `users` (`username`, `password`) VALUES(?, ?)");
$stmt->bind_param("ss", $username, $passwordHash);
$stmt->execute();
// Check user password
$stmt = $mysqli->prepare("SELECT `password` FROM `users` WHERE `username`=?");
$stmt->bind_param("s", $username);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
if (password_verify($password, $row['password']) {
echo "Password correct";
} else {
echo "Password incorrect!";
}
?>

Password Hashing Not Working For MySQL

I have been on here all day and looked at all of the answered wuestions and also looked at tutorials online regarding password hashing. It seems as though I am doing it right and it hashes the password in the database but when I go to login it tells me that the password is incorrect. Here is the script, any help would be greatly appreciated.
Login.PHP
if (isset($_POST['username'])){
//escapes special characters in a string
$username = stripslashes($_REQUEST['username']);
$username = mysqli_real_escape_string($con,$username);
$password = $_REQUEST['password'];
$password = mysqli_real_escape_string($con,$password);
//Checking is user existing in the database or not
$query = "SELECT * FROM `users` WHERE username='$username'";
$result = mysqli_query($con,$query) or die(mysql_error());
$rows = mysqli_num_rows($result);
$row = mysqli_fetch_array($result);
$hash = $row['password'];
if (password_verify($password, $hash)) {
$_SESSION['username'] = $username;
// Redirect user to index.php
$position = $row['position'];
if ( $position == "freelancer" ){
header("Location: ../freelancer/index.php");
}
elseif ($position == "employer"){
header("Location: ../employer/index.php");
}
}
else{
echo "<div class='form'>
<h3>Username/password is incorrect.</h3>
".$hash." " .$password. "
<br />Click here to <a href='login.php'>Login</a>
</div>";
Register.PHP (Piece of Code that Hashes the Password)
//BEGINNING CODE HERE
$password = stripslashes($_REQUEST['password']);
$password = mysqli_real_escape_string($con,$password);
$hashPassword = password_hash($password, PASSWORD_DEFAULT);
$sql_u = "SELECT username FROM users WHERE username='$username'";
$sql_e = "SELECT email FROM users WHERE email='$email'";
$res_u = mysqli_query($con, $sql_u);
$res_e = mysqli_query($con, $sql_e);
if (mysqli_num_rows($res_u) > 0) {
$name_error = "Sorry... username already taken";
}
else if(mysqli_num_rows($res_e) > 0){
$email_error = "Sorry... email already taken";
}
else{
$query = "INSERT INTO users (username, email, password)
VALUES ('$username', '$email', '$hashPassword')";
$results = mysqli_query($con, $query);
mkdir("../profilePics/" . $username);
echo 'You Have Registered Successfully!<br>
To Login Go To Our Login Page
';
exit();
}
}
?>
I know there may be more things wrong with this code But I am only interested in getting a basic understanding of password hashing.
$password = mysqli_real_escape_string($con,$password);
You password is now escaped and it certainly won't match the hash.
Better remove this line and look for a better way to ensure the string is safe.
What does escape means?
if your password contains "
it will turns into \"
FYI
Should I mysql_real_escape_string the password entered in the registration form?

PDO Login System With Username and Email

I'm trying to figure out how to use PDO to login to my site give the user the option of either their email address or username once they are logged in, I checked some of the other answers but it doesn't seem to work for me.
Here is the code
<?php
if(isset($_POST['username']) || isset($_POST['password'])){
if(!$_POST['username'] || !$_POST['password']){
$error = "Please Enter your Username and Password";
}
So the issue stems from below, I tried adding an OR on the $query as I saw it from one of the other posts on here but doing that allows the user to login through email but not with username, if I remove "OR user_email" they can login through username but not E-Mail.
if(!$error){
//No errors - lets get the users account
$query = "SELECT * FROM users WHERE user_name OR user_email = :username";
$result = $DBH->prepare($query);
$result->bindParam(':username', $_POST['username']);
$result->execute();
$row = $result->fetch(PDO::FETCH_ASSOC);
if($row){
//User found - let’s check the password
if(password_verify($_POST['password'], $row['user_password'])){
$_SESSION['loggedin'] = true;
$_SESSION['userData'] = $row;
echo "<script> window.location.assign('index.php?p=viewprofile'); </script>";
}else{
$error = "Username/Password Incorrect";
}
}else{
$error = "Username/Password Incorrect";
}
}
}
?>
You SQL query is wrong:
$query = "SELECT * FROM users WHERE user_name = :username OR user_email = :username";
You forgot to compare the column user_name with the user input

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.

Categories