Erik Nucibella Erik Nucibella - 1 year ago 57
Javascript Question

PHP - How to return an error message to a register page

i'm having issues in returning an error message into a register form: I have 2 files (register.php and process_register.php),
Pratically into register.php ther's the form from which i pass the request thought POST, while in process_login is executed a function (register($conn,$username,$password))

Here are the code of the files

process_register.php

<?php
if((include 'db_connect.php')==TRUE){echo"OKDB";}
if((include 'functions.php')==TRUE){echo"OKFUNCTIONS";}

sec_session_start();
if(login_check($conn) == true) //Already Logged In!
header('Location: ./index.php');

else{
if(isset($_POST['username'], $_POST['password'])) {
//Got username and pswd
$username=$_POST['username'];
$password = $_POST['password'];

$registerresult=register($conn,$username,$password);

if($registerresult==TRUE) //Registration success!
header('location: login.php');
else
header('location: register.php');

}else {
// Not here with a post request.
echo 'Invalid Request';
}
}

?>


register($conn,$username,$password)

function register($conn,$username,$password){

//ifusernamealreadyused

$alreadyregister="SELECT * FROM User WHERE username='$username';";
$query_alreadyregister=mysqli_query($conn,$alreadyregister);
$alreadyregister_rows=mysqli_num_rows($query_alreadyregister);

if($alreadyregister_rows!=0) //UsernameAlreadyUsed
return false;
else{ //UsernameNotAlreadyUsed

//RegistrationOK!
$registration="INSERT INTO User(username,password) VALUES('$username',sha2('$password',512));";
$query_registration=mysqli_query($conn,$registration);
return true;
}//UsernameNotAlreadyUsed

} //Register


My question is: How can i show a message into the form if the username is not 'correct?(returns false)
Cheers in advance!

Answer Source

This is quite simple just add these lines in your existing code

change this header('location: register.php'); to

 header('location: register.php?message=username already exist');

and in your register.php check for this

<?php if(isset($_GET['message'])) {echo $_GET['message'];} ?>