$ _SESSION不工作[PHP]

时间:2017-11-18 15:01:03

标签: php session

我知道有很多类似的问题,我尝试了很多但是仍然无效。

这是我的createAccount.php

<?php
session_start();
include("createAccount.html");
if(isset($_POST["createAccount"])) {
    include("Database.php");
    $username = $_POST["username"];
    $email = $_POST["email"];
    $password = $_POST["password"];

    echo $password;
    echo $username;

    $createAccount = "INSERT INTO users" . "(username, email, password)" . "VALUES('$username', '$email', '$password')";

    $checkUsername = "SELECT username FROM users WHERE username='$username'";
    $checkEmail = "SELECT email FROM users WHERE email='$email'";

    $result = $connected->query($checkUsername);
    $emailResults = $connected->query($checkEmail);
    if($result->num_rows == 0) {
        if($emailResults->num_rows==0){
            $connected->query($createAccount);
            //echo "Account Created";
        } else {
            //echo "Email in use";
            $emailInUse = "Email already in use";
            $_SESSION["emailInUse"] = $emailInUse;
        }
    } else {
        echo //"Username already exists";
        $accountExists = "Username already exists";
        $_SESSION["accountExists"] = $accountExists;
    }
}
?>

这里是test.php(测试会话是否有效)

<?php
session_start();

echo $_SESSION["accountExists"];
echo $_SESSION["emailInUse"];
?>

我正在尝试回显变量$ accountExists和$ emailInUse的内容,这样就是结果:     此用户名已存在     电子邮件已在使用中

但是我收到了一个未定义的索引错误。

1 个答案:

答案 0 :(得分:-1)

<强>问题

变量 $ _ SESSION [&#34; accountExists&#34;] $ _ SESSION [&#34; emailInUse&#34;] 仅在<< em> $ result-&gt; num_rows == 0 条件为真。这意味着如果您提供的电子邮件和帐户不存在,则不会初始化变量。在这种情况下,如果您看到 test.php ,它会给出错误,因为会话变量使用不存在。

<强>解决方案

在循环外声明变量并使用表示&#34;已经存在的特定字符串初始化它们&#34;问题没有发生

代码段

$_SESSION["emailInUse"] = "False";
$_SESSION["accountExists"] = "False";
if($result->num_rows == 0) {
    if($emailResults->num_rows==0){
        $connected->query($createAccount);
        //echo "Account Create    
    } else {
            $_SESSION["emailInUse"] = "True"; //or the message string
        }
    } else {
        $_SESSION["accountExists"] = "True"; //or the message string
}

然后您可以进行如下验证

<?php
    session_start();

    if($_SESSION["emailInUse"] == "True") {
        /take action
        echo "Sorry, this email is already in use";
    }

    if($_SESSION["accountExists"] == "True") {
        /take action
        echo "Sorry, this account is already exit";
    }   
?>

希望这会有所帮助;)