Form not submitting user input to database - PHP HTML - php

I have a simple form set up using html and php, I want the user inputs on signup to be saved into my database table called student with the following attributes: firstName, lastName, username, email & pswrd.
After filling the html form out, I seem to be getting the error in the URL of: "http://localhost:8888/PRCO304/signup.php?error=emptyfields&uname=kakakakakak&mail=kay#kay.com"
Please could someone take a look to see what on earth I'm doing wrong please. Nothing gets inserted into the DB?
scripts/signup-script.php:
<?php
// Checking whether the user got to this page by clicking the proper signup button.
if (isset($_POST['signup-submit'])) {
// We include the connection script so we can use it later.
// We don't have to close the MySQLi connection since it is done automatically, but it is a good habit to do so anyways since this will immediately return resources to PHP and MySQL, which can improve performance.
require 'db.php';
$firstName = $_POST['first-name'];
$lastName = $_POST['last-name'];
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['pwd'];
$passwordRepeat = $_POST['pwd-repeat'];
if (empty($firstName) || empty($lastName) || empty($username) || empty($email) || empty($password) || empty($passwordRepeat)) {
header("Location: ../signup.php?error=emptyfields&uname=".$username."&mail=".$email);
exit();
}
// Check for an invalid username AND invalid e-mail.
else if (!preg_match("/^[a-zA-Z0-9]*$/", $username) && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
header("Location: ../signup.php?error=invalidunamemail");
exit();
}
// We check for an invalid username. In this case ONLY letters and numbers.
else if (!preg_match("/^[a-zA-Z0-9]*$/", $username)) {
header("Location: ../signup.php?error=invaliduname&mail=".$email);
exit();
}
// We check for an invalid e-mail.
else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
header("Location: ../signup.php?error=invalidmail&uname=".$username);
exit();
}
// We check if the repeated password is NOT the same.
else if ($password !== $passwordRepeat) {
header("Location: ../signup.php?error=passwordcheck&uname=".$username."&mail=".$email);
exit();
}
else {
// First we create the statement that searches our database table to check for any identical usernames.
$sql = "SELECT username FROM student WHERE username = ?;";
// We create a prepared statement.
$stmt = mysqli_stmt_init($conn);
// Then we prepare our SQL statement AND check if there are any errors with it.
if (!mysqli_stmt_prepare($stmt, $sql)) {
// If there is an error we send the user back to the signup page.
header("Location: ../signup.php?error=sqlerror");
exit();
}
else {
// Next we need to bind the type of parameters we expect to pass into the statement, and bind the data from the user.
// In case you need to know, "s" means "string", "i" means "integer", "b" means "blob", "d" means "double".
mysqli_stmt_bind_param($stmt, "s", $username);
// Then we execute the prepared statement and send it to the database!
mysqli_stmt_execute($stmt);
// Then we store the result from the statement.
mysqli_stmt_store_result($stmt);
// Then we get the number of result we received from our statement. This tells us whether the username already exists or not!
$resultCount = mysqli_stmt_num_rows($stmt);
// Then we close the prepared statement!
mysqli_stmt_close($stmt);
// Here we check if the username exists.
if ($resultCount > 0) {
header("Location: ../signup.php?error=usertaken&mail=".$email);
exit();
}
else {
// If we got to this point, it means the user didn't make an error! :)
// Next thing we do is to prepare the SQL statement that will insert the users info into the database. We HAVE to do this using prepared statements to make this process more secure. DON'T JUST SEND THE RAW DATA FROM THE USER DIRECTLY INTO THE DATABASE!
// Prepared statements works by us sending SQL to the database first, and then later we fill in the placeholders (this is a placeholder -> ?) by sending the users data.
$sql = "INSERT INTO student (firstName, lastName, username, email, pswrd) VALUES (?, ?, ?, ?, ?);";
// Here we initialize a new statement using the connection from the db.php file.
$stmt = mysqli_stmt_init($conn);
// Then we prepare our SQL statement AND check if there are any errors with it.
if (!mysqli_stmt_prepare($stmt, $sql)) {
// If there is an error we send the user back to the signup page.
header("Location: ../signup.php?error=sqlerror");
exit();
}
else {
$hashedPwd = password_hash($password, PASSWORD_DEFAULT);
mysqli_stmt_bind_param($stmt, "sssss", $firstName, $lastName, $username, $email, $hashedPwd);
// Then we execute the prepared statement and send it to the database!
// This means the user is now registered! :)
mysqli_stmt_execute($stmt);
// Lastly we send the user back to the signup page with a success message!
header("Location: ../signup.php?signup=success");
exit();
}
}
}
}
// Then we close the prepared statement and the database connection!
mysqli_stmt_close($stmt);
mysqli_close($conn);
}
else {
// If the user tries to access this page an inproper way, we send them back to the signup page.
header("Location: ../signup.php");
exit();
}
signup.php:
<?php
// Here we create an error messages if the user made an error trying to sign up.
if (isset($_GET["error"])) {
if ($_GET["error"] == "emptyfields") {
echo '<p class="signuperror">Fill in all fields!</p>';
}
else if ($_GET["error"] == "invalidunamedmail") {
echo '<p class="signuperror">Invalid username and email!</p>';
}
else if ($_GET["error"] == "invaliduname") {
echo '<p class="signuperror">Invalid username!</p>';
}
else if ($_GET["error"] == "invalidmail") {
echo '<p class="signuperror">Invalid email!</p>';
}
else if ($_GET["error"] == "passwordcheck") {
echo '<p class="signuperror">Your passwords do not match!</p>';
}
else if ($_GET["error"] == "usertaken") {
echo '<p class="signuperror">Username is already taken!</p>';
}
}
// Here we create a success message if the new user was created.
else if (isset($_GET["signup"])) {
if ($_GET["signup"] == "success") {
echo '<p class="signupsuccess">Signup successful!</p>';
}
}
?>
<form action="scripts/signup-script.php" method="post">
<div class="signupContainer">
<h1>Sign Up</h1>
<p>Please fill in this form to create an account.</p>
<hr>
<?php
if (!empty($_GET["first-name"])) {
echo '<label for="first-name"><b>First Name</b></label>
<input type="text" placeholder="First Name" name="first-name" value="'.$_GET["first-name"].'">';
} else {
echo '<label for="first-name"><b>First Name</b></label>
<input type="text" placeholder="First Name" name="first-name">';
}
if (!empty($_GET["last-name"])) {
echo '<label for="last-name"><b>Last Name</b></label>
<input type="text" placeholder="Last Name" name="last-name" value="'.$_GET["last-name"].'">';
} else {
echo '<label for="last-name"><b>Last Name</b></label>
<input type="text" placeholder="Please Enter Last Name" name="last-name">';
}
if (!empty($_GET["username"])) {
echo '<label for="username"><b>Username</b></label>
<input type="text" placeholder="Username" name="username" value="'.$_GET["username"].'">';
} else{
echo '<label for="username"><b>Username</b></label>
<input type="text" placeholder="Username" name="username">';
}
if (!empty($_GET["email"])) {
echo '<label for="email"><b>Email</b></label>
<input type="text" placeholder="Email" name="email" value="'.$_GET["email"].'">';
} else {
echo '<label for="email"><b>Email</b></label>
<input type="text" placeholder="Email" name="email">';
}
?>
<label for="psw"><b>Password</b></label>
<input type="password" placeholder="Password" name="psw">
<label for="psw-repeat"><b>Repeat Password</b></label>
<input type="password" placeholder="Repeat Password" name="psw-repeat">
<label>
<input type="checkbox" checked="checked" name="remember"> Remember me
</label>
<p>By creating an account you agree to our Terms & Privacy.</p>
<div class="clearfix">
<button type="submit" class="signupBtn" name="signup-submit">Sign Up</button>
</div>
</div>
</form>

The issue is that your form has name="psw" and name="psw-repeat" while your script looks for $_POST['pwd']; and $_POST['pwd-repeat']; psw vs pwd
While we're at it, we could simplify the scripts a bit:
scripts/signup-script.php:
<?php
// Checking whether the user got to this page by clicking the proper signup button.
if (!isset($_POST['signup-submit'])) {
// If the user tries to access this page an inproper way, we send them back to the signup page.
header('Location: ../signup.php');
exit();
}
// We include the connection script so we can use it later.
// We don't have to close the MySQLi connection since it is done automatically,
// but it is a good habit to do so anyways since this will immediately return
// resources to PHP and MySQL, which can improve performance.
require 'db.php';
$firstName = !empty($_POST['first-name']) ? $_POST['first-name'] :'';
$lastName = !empty($_POST['last-name']) ? $_POST['last-name'] : '';
$username = !empty($_POST['username']) ? $_POST['username'] : '';
$email = !empty($_POST['email']) ? $_POST['email'] : '';
$password = !empty($_POST['pwd']) ? $_POST['pwd'] : '';
$passwordRepeat = !empty($_POST['pwd-repeat']) ? $_POST['pwd-repeat'] : '';
$location = null;
switch (true) {
case !$firstName || !$lastName || !$username || !$email || !$password || !$passwordRepeat:
$location = "Location: ../signup.php?error=emptyfields&uname=$username&mail=$email";
break;
case !preg_match('/^[a-zA-Z0-9]*$/', $username) && !filter_var($email, FILTER_VALIDATE_EMAIL):
// Check for an invalid username AND invalid e-mail.
$location = 'Location: ../signup.php?error=invalidunamemail';
break;
case !preg_match('/^[a-zA-Z0-9]*$/', $username):
// We check for an invalid username. In this case ONLY letters and numbers.
$location = "Location: ../signup.php?error=invaliduname&mail=$email";
break;
case !filter_var($email, FILTER_VALIDATE_EMAIL):
// We check for an invalid e-mail.
$location = "Location: ../signup.php?error=invalidmail&uname=$username";
break;
case $password !== $passwordRepeat:
// We check if the repeated password is NOT the same.
$location = "Location: ../signup.php?error=passwordcheck&uname=$username&mail=$email";
break;
}
// if we had errors, stop here
if ($location) {
header($location);
exit();
}
// First we create the statement that searches our database table to check for any identical usernames.
$sql = "SELECT username FROM student WHERE username = ?;";
// We create a prepared statement.
$stmt = mysqli_stmt_init($conn);
// Then we prepare our SQL statement AND check if there are any errors with it.
if (!mysqli_stmt_prepare($stmt, $sql)) {
// If there is an error we send the user back to the signup page.
header("Location: ../signup.php?error=sqlerror");
exit();
}
// Next we need to bind the type of parameters we expect to pass into the statement, and bind the data from the user.
// In case you need to know, "s" means "string", "i" means "integer", "b" means "blob", "d" means "double".
mysqli_stmt_bind_param($stmt, "s", $username);
// Then we execute the prepared statement and send it to the database!
mysqli_stmt_execute($stmt);
// Then we store the result from the statement.
mysqli_stmt_store_result($stmt);
// Then we get the number of result we received from our statement. This tells us whether the username already exists or not!
$resultCount = mysqli_stmt_num_rows($stmt);
// Then we close the prepared statement!
mysqli_stmt_close($stmt);
// Here we check if the username exists.
if ($resultCount > 0) {
header("Location: ../signup.php?error=usertaken&mail=".$email);
exit();
}
// If we got to this point, it means the user didn't make an error! :)
// Next thing we do is to prepare the SQL statement that will insert the users info into the database. We HAVE to do this using prepared statements to make this process more secure. DON'T JUST SEND THE RAW DATA FROM THE USER DIRECTLY INTO THE DATABASE!
// Prepared statements works by us sending SQL to the database first, and then later we fill in the placeholders (this is a placeholder -> ?) by sending the users data.
$sql = "INSERT INTO student (firstName, lastName, username, email, pswrd) VALUES (?, ?, ?, ?, ?);";
// Here we initialize a new statement using the connection from the db.php file.
$stmt = mysqli_stmt_init($conn);
// Then we prepare our SQL statement AND check if there are any errors with it.
if (!mysqli_stmt_prepare($stmt, $sql)) {
// If there is an error we send the user back to the signup page.
$error = mysqli_stmt_error($stmt);
header("Location: ../signup.php?error=sqlerror&description=$error");
exit();
}
$hashedPwd = password_hash($password, PASSWORD_DEFAULT);
mysqli_stmt_bind_param($stmt, "sssss", $firstName, $lastName, $username, $email, $hashedPwd);
// Then we execute the prepared statement and send it to the database!
// This means the user is now registered! :)
mysqli_stmt_execute($stmt);
// Lastly we send the user back to the signup page with a success message!
header("Location: ../signup.php?signup=success");
// Then we close the prepared statement and the database connection!
mysqli_stmt_close($stmt);
mysqli_close($conn);
exit();
signup.php:
<?php
$statusMessage = '';
if (isset($_GET['error'])) {
// Here we create an error messages if the user made an error trying to sign up.
$errorMap = [
'emptyfields' => 'Fill in all fields!',
'invalidunamedmail' => 'Invalid username and email!',
'invaliduname' => 'Invalid username!',
'invalidmail' => 'Invalid email!',
'passwordcheck' => 'Your passwords do not match!',
'usertaken' => 'Username is already taken!',
];
$message = $errorMap[$_GET['error']] ?: 'An unknown error occurred';
$statusMessage = "<p class='signuperror'>$message</p>";
}
else if (isset($_GET['signup']) && $_GET['signup'] === 'success') {
// Here we create a success message if the new user was created.
$statusMessage = '<p class="signupsuccess">Signup successful!</p>';
}
$firstName = !empty($_GET['first-name']) ? $_GET['first-name'] :'';
$lastName = !empty($_GET['last-name']) ? $_GET['last-name'] : '';
$username = !empty($_GET['username']) ? $_GET['username'] : '';
$email = !empty($_GET['email']) ? $_GET['email'] : '';
$password = !empty($_GET['pwd']) ? $_GET['pwd'] : '';
$passwordRepeat = !empty($_GET['pwd-repeat']) ? $_GET['pwd-repeat'] : '';
?>
<?= $statusMessage ?>
<form action="scripts/signup-script.php" method="post">
<div class="signupContainer">
<h1>Sign Up</h1>
<p>Please fill in this form to create an account.</p>
<hr>
<label for="first-name"><b>First Name</b></label>
<input type="text" placeholder="First Name" name="first-name" value="<?= $firstName ?>">
<label for="last-name"><b>Last Name</b></label>
<input type="text" placeholder="Last Name" name="last-name" value="<?= $lastName ?>">
<label for="username"><b>Username</b></label>
<input type="text" placeholder="Username" name="username" value="<?= $username ?>">
<label for="email"><b>Email</b></label>
<input type="text" placeholder="Email" name="email" value="<?= $email ?>">
<label for="psw"><b>Password</b></label>
<input type="password" placeholder="Password" name="pwd">
<label for="psw-repeat"><b>Repeat Password</b></label>
<input type="password" placeholder="Repeat Password" name="pwd-repeat">
<label>
<input type="checkbox" checked="checked" name="remember"> Remember me
</label>
<p>By creating an account you agree to our Terms & Privacy.</p>
<div class="clearfix">
<button type="submit" class="signupBtn" name="signup-submit">Sign Up</button>
</div>
</div>
</form>

Related

lock a page behind a password

I'm trying to lock out a certain page to one user, with a username and a password. I tried a couple things, but what I think I need is a sort of login function. I have made logins before, so I used code of mine that I used before. For some reason however, it gives me an error that I coded in to know that the password is incorrect, even though it isn't. To make it a bit easier to see which specific error message is given, I've put in a 1 and a 2 behind the error, i get error number 1.
Below is my php code and below that is my html form I use.
$username = $password = "";
$username_err = $password_err = $login_err = "";
function pr($data, $kill_script = false)
{
echo '<pre>'.print_r($data,1).'</pre>';
if($kill_script) exit;
}
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Check if username is empty
if(empty(trim($_POST["username"]))){
$username_err = "Please enter username.";
}
else{
$username = trim($_POST["username"]);
}
// Check if password is empty
if(empty(trim($_POST["password"]))){
$password_err = "Please enter your password.";
}
else{
$password = trim($_POST["password"]);
}
// Validate Credentials
if(empty($username_err) && empty($password_err)){
//prepare a select statement
$sql = "SELECT username, password FROM user_confirm WHERE username = :username";
if($stmt = $conn->prepare($sql)){
// bind variables to the prepared statement as parameters
$stmt->bindParam(":username", $param_username, PDO::PARAM_STR);
//set parameters
$param_username = trim($_POST["username"]);
if($stmt->execute()){
// check if username exits, if yes then verify password
if($stmt->rowCount() == 1){
if($row = $stmt->fetch()){
$username = $row["username"];
$hashed_password = $row["password"];
if(password_verify($password, $hashed_password)){
// password is correct, so start new session
session_start();
//store data in session variables
$_SESSION["loggedin"] = true;
$_SESSION["username"] = $username;
//redirect user to welcome page
header("location: werk_edit.php");
}
else{
//invalid password, display error message
$login_err = "Invalid username or password. 1";
}
}
}
else{
//username doesn't exist, display error message
$login_err = "Invalid username or password. 2";
}
}
else{
echo "Something went wrong, please try again later.";
}
//close statement
unset($stmt);
}
}
//close connection
unset($conn);
}
HTML Form:
<?php
if(!empty($login_err)){
echo '<div class="alert alert-danger">' . $login_err . '</div>';
}
?>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<label>Username</label>
<input type="text" name="username" class="form-control <?php echo (!empty($username_err)) ? 'is-invalid' : ''; ?>" value="<?php echo $username; ?>">
<span class="invalid-feedback"><?php echo $username_err; ?></span>
<label>Password</label>
<input type="password" name="password" class="form-control <?php echo (!empty($password_err)) ? 'is-invalid' : ''; ?>">
<span class="invalid-feedback"><?php echo $password_err; ?></span>
<input type="submit" name="login" class="btn btn-primary" value="Login">
</form>

Change signup page echo message based on if statement from different page

I am practicing PHP and database creation and would like to change my message based on errors from the input. I can't figure out how to pass the changed messaged back and would appreciate any help given.
This is my sign up page
<main>
<h1>Signup<h1>
<h3>
<?php
echo $errorMsg;
?>
<h3>
<form action="includes/signup.inc.php" method="post">
<input type="text" name="uid" placeholder="Username">
<input type="text" name="mail" placeholder="E-mail">
<input type="password" name="pwd" placeholder="Password">
<input type="password" name="pwd_repeat" placeholder="Repeat Password">
<button type="submit" name="signup-submit">Submit</button>
<form>
</main>
This is my processing page
if(isset($_POST['signup-submit'])){
require 'dbh.inc.php';
$Name = $_POST['uid'];
$Email= $_POST['mail'];
$Password = $_POST['pwd'];
$PasswordRepeat = $_POST['pwd_repeat'];
if(empty($Name) || empty($Email) || empty($Password) || empty($PasswordRepeat)){
header("Location: ../signup.php?error=emptyfields=1"); //Check if any field is empty
exit();
}
else if(!filter_var($Email, FILTER_VALIDATE_EMAIL) && !preg_match("/^[a-zA-Z0-9]*$/", $Name)){
header("Location: ../signup.php?error=invalidamil&uid"); //Check if username and email is valid input
exit();
}
else if(!filter_var($Email, FILTER_VALIDATE_EMAIL)){
header("Location: ../signup.php?error=invalidamil&uid=".$Name); //Check if email is valid input
exit();
}
else if($Password !== $PasswordRepeat){
header("Location: ../signup.php?error=passwordCheck&uid=".$Name."&mail=".$Email); // Check if passwords don't match
exit();
}
$sql2 = "SELECT UserName FROM dbo.MainTable WHERE UserName = ?";
$params2 = array($Name, SQLSRV_PARAM_IN);
$stmt2 = sqlsrv_query($conn, $sql2, $params2);
if($stmt2 === false)
{
die(print_r(sqlsrv_errors(), true));
exit();
}
$row_count = sqlsrv_num_rows($stmt2);
if($row_count != 0)
{
$_SESSION['errMsg'] = "Error retrieving username";
header("location: ../register.php");
exit();
}
else if($row_count > 0)
{
$_SESSION['errMsg'] = "Username is already used";
header("Location: ../signup.php?error=UserNameTaken&uid");
exit();
}
else{
$sql = "INSERT INTO dbo.MainTable(UserName,Email,UserPassword)
VALUES (?,?,?)";
$Password = PASSWORD_HASH($_POST['pwd'], PASSWORD_DEFAULT); //Password hashing
$stmt = sqlsrv_query($conn, $sql,array(#$Name,#$Email,#$Password));
if($stmt === false){
die( print_r( sqlsrv_errors(), true));
}else{
$_SESSION['errMsg'] = "Registration completed!";
header("Location: ../signup.php?signup=COMPLETE");
exit();
}
}
I am not sure where to put a change message variable here because I couldn't get it work in the if statements.
You are providing the error message as an url paramenter, so you can access it with php $_GET
<h3>
<?php
echo $_GET['error'];
?>
<h3>

Issue updating SQL variables

I have been attempting to update my SQL database which worked 100% with just updating the password. Once I try to update another variable in my database it just refreshes the page! I have been trying and looking at examples for hours, any help would be greatly appreciated. I believe the error is somewhere in my SQL code along with binding the variables to the prepared statement line. Other than that I have no idea where to start. So any direction would help as well!
PHP:
<?php
// Initialize the session
session_start();
// Check if the user is logged in, if not then redirect to login page
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
header("location: login.php");
exit;
}
// Include config file
require_once "config.php";
// Define variables and initialize with empty values
$new_password = $confirm_password = "";
$new_password_err = $confirm_password_err = "";
$new_discordusername = $_SESSION["DiscordUsername"];
$new_steamid = $_SESSION["steamid"];
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Validate new password
if(empty(trim($_POST["new_password"]))){
$new_password_err = "Please enter the new password.";
} elseif(strlen(trim($_POST["new_password"])) < 6){
$new_password_err = "Password must have atleast 6 characters.";
} else{
$new_password = trim($_POST["new_password"]);
$new_discordusername = trim($_POST["new_discord"]);
$new_steamid = trim($_POST["new_steam"]);
}
// Validate confirm password
if(empty(trim($_POST["confirm_password"]))){
$confirm_password_err = "Please confirm the password.";
} else{
$confirm_password = trim($_POST["confirm_password"]);
if(empty($new_password_err) && ($new_password != $confirm_password)){
$confirm_password_err = "Password did not match.";
}
}
// Check input errors before updating the database
if(empty($new_password_err) && empty($confirm_password_err)){
// Prepare an update statement
$sql = "UPDATE users SET
password = ?,
steamid = ?
WHERE id = ?";
if($stmt = mysqli_prepare($link, $sql)){
// Set parameters
$param_password = password_hash($new_password, PASSWORD_DEFAULT);
$param_id = $_SESSION["id"];
$param_discordusername = $new_discordusername;
$param_steamid = $new_steamid;
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "ssi", $param_password, $param_steamid, $param_id);
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
// Password updated successfully. Destroy the session, and redirect to login page
session_destroy();
header("location: login.php");
exit();
} else{
echo "Oops! Something went wrong. Please try again later." + mysqli_error($link);
}
// Close statement
mysqli_stmt_close($stmt);
}
}
// Close connection
mysqli_close($link);
}
?>
FORM:
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<!--STEAM ID-->
<div class="form-group ">
<label>Steam ID:</label>
<input type="text" name="new_steam" class="form-control" value="<?php echo $new_steamid; ?>">
</div>
<!--DISCORD NAME-->
<div class="form-group">
<label>Discord Username:</label>
<input type="text" name="new_discord" class="form-control" value="<?php echo $new_discordusername; ?>">
</div>
<!--OLD PASSWORD-->
<div class="form-group <?php echo (!empty($new_password_err)) ? 'has-error' : ''; ?>">
<label>New Password</label>
<input type="password" name="new_password" class="form-control" value="<?php echo $new_password; ?>">
<span style ="color:red;" class="help-block"><?php echo $new_password_err; ?></span>
</div>
<!--NEW PASSWORD-->
<div class="form-group <?php echo (!empty($confirm_password_err)) ? 'has-error' : ''; ?>">
<label>Confirm Password</label>
<input type="password" name="confirm_password" class="form-control">
<span style ="color:red;" class="help-block"><?php echo $confirm_password_err; ?></span>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Submit">
<a class="btn btn-link" href="console.php">Cancel</a>
</div>
</form>

Insert statement only inserting some of the data to the database

I hope my title makes sense, cause I don't know how to phrase it any shorter.
I am doing a login and sign up form with parameters and hashing. I have used parameters before but never in a signup form.
So the issue it that when I make a new a user it ONLY inserts the password but not the username. I have tried to change the name of the username, I have checked the connection to the database is correct and I am simply lost of what to do now.
My database can be seen here:
$username = $password = $confirm_password = "";
$username_err = $password_err = $confirm_password_err = "";
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Validate username
if(empty(trim($_POST["username"]))){
$username_err = "Please enter a username.";
} else{
// Prepare a select statement
$sql = "SELECT id FROM user WHERE username = ?";
if($stmt = mysqli_prepare($conn, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "s", $param_username);
// Set parameters
$param_username = trim($_POST["username"]);
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
/* store result */
mysqli_stmt_store_result($stmt);
if(mysqli_stmt_num_rows($stmt) == 1){
$username_err = "This username is already taken.";
} else{
$username = trim($_POST["username"]);
}
} else{
echo "Oops! Something went wrong. Please try again later.";
}
}
// Close statement
mysqli_stmt_close($stmt);
}
// Validate password
if(empty(trim($_POST['password']))){
$password_err = "Please enter a password.";
} elseif(strlen(trim($_POST['password'])) < 6){
$password_err = "Password must have atleast 6 characters.";
} else{
$password = trim($_POST['password']);
}
// Validate confirm password
if(empty(trim($_POST["confirm_password"]))){
$confirm_password_err = 'Please confirm password.';
} else{
$confirm_password = trim($_POST['confirm_password']);
if($password != $confirm_password){
$confirm_password_err = 'Password did not match.';
}
}
// Check input errors before inserting in database
if(empty($username_err) && empty($password_err) &&
empty($confirm_password_err)){
// Prepare an insert statement
$sql = "INSERT INTO user (name, password) VALUES (?, ?)";
if($stmt = mysqli_prepare($conn, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "ss", $param_username,
$param_password);
// Set parameters
$param_username = $username;
$param_password = password_hash($password, PASSWORD_DEFAULT);
// Creates a password hash
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
// Redirect to login page
// header("location: login.php");
echo "You have been added";
} else{
echo "Something went wrong. Please try again later.";
}
}
// Close statement
mysqli_stmt_close($stmt);
}
// Close connection
mysqli_close($conn);
}
?>
<?php
include "header.php";
?>
<div class="wrapper">
<h2>Sign Up</h2>
<p>Please fill this form to create an account.</p>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?
>" method="post">
<div class="form-group <?php echo (!empty($username_err)) ?
'has-error' : ''; ?>">
<label>Username</label>
<input type="text" name="username"class="form-control"
value="<?php echo $username; ?>">
<span class="help-block"><?php echo $username_err; ?>
</span>
</div>
<div class="form-group <?php echo (!empty($password_err)) ?
'has-error' : ''; ?>">
<label>Password</label>
<input type="password" name="password" class="form-control"
value="<?php echo $password; ?>">
<span class="help-block"><?php echo $password_err; ?>
</span>
</div>
<div class="form-group <?php echo
(!empty($confirm_password_err)) ? 'has-error' : ''; ?>">
<label>Confirm Password</label>
<input type="password" name="confirm_password" class="form-
control" value="<?php echo $confirm_password; ?>">
<span class="help-block"><?php echo $confirm_password_err;
?></span>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary"
value="Submit">
<input type="reset" class="btn btn-default" value="Reset">
</div>
<p>Already have an account? Login here.
</p>
</form>
</div>
<footer>
<?php
include "footer.php";
?> </footer>
Hope you can help me, feel free to ask questions if I haven't made myself clear enough :)
Remove the following line
$param_username = $username;
Because you overwrite $param_username that is already set with trim($_POST["username"])
Have a nice day.
It turnes out the $username = $password = $confirm_password = ""; was clearing my textbox so I removed it and added a $username = $_POST["username"]; and then the code worked.

How to display validation errors in my website?

I just want this PHP code to display form validation errors in my website whenever someone uses the form incorrectly. Here is the code and I will also include the HTML of the form.
The code is only for reference, if you have a better way of doing it, then please show me.
<?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']);
$number = mysqli_real_escape_string($conn, $_POST['number']);
$uid = mysqli_real_escape_string($conn, $_POST['uid']);
$pwd = mysqli_real_escape_string($conn, $_POST['pwd']);
// Error handlers
// Check for empty fields
if (empty($first) || empty($last) || empty($email) || empty($number) || empty($uid) || empty($pwd)) {
header("Location: ../signup.php?signup=empty");
exit();
} else {
// Check if input characters are valid
if (!preg_match("/^[a-zA-Z'-]+$/",$first) || !preg_match("/^[a-zA-Z'-]+$/",$last)) {
header("Location: ../signup.php?signup=invalid");
exit();
} else {
// Check if email is valid
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
header("Location: ../signup.php?signup=invalidemail");
exit();
} else {
if (preg_match("/^[0-9]{3}-[0-9]{4}-[0-9]{4}$/", $number)) {
header("Location: ../signup.php?signup=invalidnumber");
exit();
} else {
$sql = "SELECT * FROM users WHERE user_uid='$uid'";
$result = mysqli_query($conn, $sql);
$resultcheck = mysqli_num_rows($result);
if ($resultcheck > 0) {
header("Location: ../signup.php?signup=usertaken");
exit();
} else {
// Hashing the password
$hashedPwd = password_hash($pwd, PASSWORD_DEFAULT);
// Insert the user into the database
$sql = "INSERT INTO users (user_first, user_last, user_email, user_number, user_uid, user_pwd) VALUES ('$first', '$last', '$email', '$number', '$uid', '$hashedPwd');";
mysqli_query($conn, $sql);
header("Location: ../accountcreated.php");
exit();
}
}
}
}
} else {
header("Location: ../signup.php");
exit();
}
Here is the HTML code:
<form class="memberform" action="includes/signup.inc.php" method="POST" novalidate>
<input id="spfirst" class="form_fname" type="text" name="first" placeholder="First Name">
<span class="error_form"></span>
<input id="splast" class="form_lname" type="text" name="last" placeholder="Last Name">
<span class="error_form"></span>
<input class="form_email" type="email" name="email" placeholder="E-mail">
<span class="error_form"></span>
<input id="spnumber" class="form_tel" type="tel" name="number" placeholder="Phone number">
<span class="error_form"></span>
<input id="spuser" class="form_user" type="text" name="uid" placeholder="Username">
<span class="error_form"></span>
<input class="form_password" type="password" name="pwd" placeholder="Password">
<span class="error_form"></span>
<button type="submit" name="submit">Create Account</button>
</form>
Okay there it is. I already tried so many things a nothing seems to work... Maybe it's due to my limited knowledge with PHP.
This is not the best way to do it in my opinion, but following your current code, I suggest you do this.
In your signup.php file, add this where you want the error message to appear (within the HTML if you want):
<?php
if(isset($_GET['signup'])){
switch($_GET['signup']){
case 'empty':
$msg = 'Empty fields';
break;
case 'invalid':
$msg = 'Invalid input';
break;
case 'invalidemail':
$msg = 'Invalid email';
break;
case 'invalidnumber':
$msg = 'Invalid number';
break;
case 'usertaken':
$msg = 'User taken';
break;
default:
$msg = ''; // Default message, if any
break;
}
echo '<div class="error_div">'.$msg.'</div>'; // here's where the message appears
}
?>
That will show your messages. Obviously, feel free to change the class name and style it as you wish.
Or you can simply do something like this (changing the text and stuff depending on the result you're looking for):
<?php
if(isset($_GET['signup'])){
if($_GET['signup'] == 'empty'){
echo '<span class="error_form">Empty values</span>';
}
}
?>
Since you're redirecting users to the signup page with a specific error message (Example: usertaken), you can use $_GET to handle the errors.
So in your signup page, do this
$error should = "" ;
if(isset($_GET['signup'])) {
$error = $_GET['signup'];
if(!empty($error){
//check for specific errors
if($error == "usertaken"){
$errorMsg = "The username has already been taken, try again";
}
}
}
You can use the $errorMsg in your HTML and put it where you want to display the error and design it accordingly.
NOTE: I have not done any sanitization, trying to keep this short.

Categories