我应该在login.php中声明我的变量会话,因为我需要此会话来显示用户数据

时间:2018-05-03 08:25:47

标签: php

我应该在哪里声明我的会话,然后如何调用我的变量会话,我需要它来显示用户数据。如果我的问题错了,请更正

这是我的条件 login.php

session_start();
$_SESSION["Username"]="$Username";
require_once '../include/DBOperations.php';
$response=array();
if($_SERVER['REQUEST_METHOD']=='POST'){
  if(isset($_POST['Username']) && isset($_POST['Password'])){
$db=new DBOperations();

  if($db->login($_POST['Username'],$_POST['Password'])){
    $response['error'] = false;
    $response['Auth'] = "Success";


  } else {
    $response['error']=true;
    $response['Auth'] = "Failed";
    $response['message']="invalid Username or Password";
  }
} else{
    $response['error']=true;
    $response['Auth'] = "Invalid";
    $response['message']="Required fields are missing";
  }
}
echo json_encode($response);
?>

这是 DBOperations.php

  function login($Username,$Password){
  $anotherConnection = mysqli_connect("localhost","root","","sisro1");

  $sql = "SELECT * FROM Pengguna WHERE Username='$Username' AND Password='$Password'";

  $result = mysqli_query($anotherConnection,$sql);
  $row = mysqli_num_rows($result);
  if ($row == 1){
    return true;
  } else {
    echo(mysqli_error($anotherConnection));
    return false;
  }

}

这是我的连接的 DBConnect.php

  function connect(){
      include_once dirname(__FILE__).'/Constrants.php';
      //$con = new mysqli(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME);
      $dbName = "sisro1";
      $dbHost = "Localhost";
      $user = "root";
      $pass = "";
      $con = new PDO("mysql:host=$dbHost;dbname=$dbName", $user, $pass);

        if(mysqli_connect_errno()){
          echo "Failed to connect with database".mysqli_connect_err();
        }
        return $this->con;
  }

1 个答案:

答案 0 :(得分:0)

你应该在登录功能的if条件下开始你的会话

 if ($row == 1){
 $_SESSION["Username"]=$Username;
 return true;
 } else {
   echo(mysqli_error($anotherConnection));
   return false;
 }