PHP - 如何将错误消息返回到注册页面

时间:2016-06-15 11:12:57

标签: javascript php jquery html forms

我在将错误消息返回到注册表单时遇到问题:我有2个文件(register.php和process_register.php), 实际上是register.php的形式,我通过POST传递请求,而在process_login中执行一个函数(寄存器($ conn,$ username,$ password))

以下是文件的代码

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';
                               }
                           }

?>

寄存器($康恩,$用户名,密码$)

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

我的问题是:如果用户名不正确,如何在表单中显示消息?(返回false)  提前干杯!

2 个答案:

答案 0 :(得分:1)

这很简单,只需在现有代码中添加这些行

即可

将此header('location: register.php');更改为

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

并在register.php检查此

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

答案 1 :(得分:0)

在您希望显示错误消息的页面中,添加:

<?php if(isset($message)) {echo $message;} ?>

修改您的注册功能:

<?php
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
   $message = 'Username already used!'; //set your error message here
   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

?>