查询后没有创建新的$ _SESSION变量?

时间:2013-10-10 10:29:22

标签: php mysql sql session

我尝试构建一个登录过程,通过使用$ _SESSION变量,存储用户的登录凭据并用于在屏幕上显示数据库中的相关数据(即他们只会看到学校他们工作的数据。)

   <?php    
session_start();

if(!isset($_SESSION['Initials'], $_SESSION['Surname']))
{

 $host = "xxx";
 $username = "xxx";
 $password = "xxx";
 $database_name = "xxx";
 $table_name = "xxx";

 mysql_connect($host, $username, $password) OR die("Can't  
 connect");
 mysql_select_db($database_name) OR die("Can't connect to 
 Database");

 $query = "SELECT Class FROM $table_name WHERE Initials = '". 
 $_SESSION['Initials']."' AND staff LIKE '%".$_SESSION['Surname']."'";
 $result = mysql_query($query);
 $class = mysql_fetch_array($result);
 $count = mysql_num_rows($result);

 if($count === NULL)
 {
  echo "ERROR";
 }
  else
  {
  $_SESSION['Class'] = $result;
  echo "Class added to sessions";
  }
}
?>

通过为if语句添加正确的括号,我可以轻松解决查询无法识别会话变量的初始问题。我在这里出现的下一个问题是,即使查询应该是成功的(我没有收到错误消息,如果$ count为FALSE或NULL,则会出现错误消息)&#39;没有将结果数组创建到新的会话中,因为当我在新页面上打印会话数组时,它仍然只会带有&#39;缩写&#39;和&#39;姓氏&#39;会话。

我需要更改为我的查询或后查询过程以便将该数组(因为它必然会抛出多个结果)进入新会话?

非常感谢我最初问题的答案!

2 个答案:

答案 0 :(得分:1)

if(!isset($_SESSION['Initials'], $_SESSION['Surname'])) {
// code
}

你需要{}括号

  

if(!isset($ _ SESSION ['Initials'],$ _SESSION ['Surname']))

     

$ host =“xxxxx”; $ username =“xxxxx”; $ password =“xxxxx”;

if(!isset($_SESSION['Initials'], $_SESSION['Surname'])) {

$host = "xxxxx";
}
$username = "xxxxx";
$password = "xxxxx";

答案 1 :(得分:0)

我找到了答案 - 事实证明我没有将其中一个会话变量视为正确的数组,因此无法正确加载。我在下面添加了我的脚本,以便将来有类似问题的人可以将它作为参考点使用:

<?php

 session_start();


 // Server Details //
 $host = "---";
 $username = "---";
 $password = "---";
 $database_name = "---";
 $table_name = "---";


 // Connect Command //
 mysql_connect($host, $username, $password) OR die("Can't  
 connect");
 mysql_select_db($database_name) OR die("Can't connect to 
 Database");


 // Query to call up the unique school name //
 $query_school = mysql_query("SELECT DISTINCT School FROM $table_name 
 WHERE Initials = '".$_SESSION['---']."'
 AND staff LIKE '%".$_SESSION['---']."'") or die( mysql_error());
 $result_school = mysql_result($query_school, 0);


 // Query to call up the unique centre no //
 $query_centreno = mysql_query("SELECT DISTINCT CentreNo FROM 
 $table_name WHERE Initials = '".$_SESSION['---']."'
 AND staff LIKE '%".$_SESSION['---']."'") or die( mysql_error());
 $result_centreno = mysql_result($query_centreno, 0);


 // The newly created sessions for school info //
 $_SESSION['---'] = $result_school;
 $_SESSION['---'] = $result_centreno;


 // Query to call up the array of classes //
 $query_class = mysql_query("SELECT Class FROM $table_name WHERE 
 Initials = '".$_SESSION['---']."'
 AND staff LIKE '%".$_SESSION['---']."'") or die( mysql_error());
 $query_class__array = array();
 while($row = mysql_fetch_assoc($query_class))
 $query_class_array[] = $row;

 $_SESSION['---'] = $query_class_array;

?>