如何从2个不同的表中获取会话变量?

时间:2015-07-27 10:35:26

标签: php mysql session

我是PHP的新人。我第一次使用会话。我在db中有两个表。第一个名为pacra_teams的表,其中包含列ID和标题。第二个表格为og_users,其中包含多列,但我使用team_title作为foreign key作为商店ID来反对团队标题。

现在我要创建一个session,并希望显示表pacra_teams中的团队名称和table og_users中的用户名。

我尝试使用代码,但我失败了。

<?php
 // starts session
 session_start();
 $servername = "localhost";
$username = "root";
$password = "";
$dbname = "pacra1";


$conn = new mysqli($servername, $username, $password, $dbname);
$sql="SELECT *
FROM og_users
LEFT JOIN pacra_teams
ON og_users.id = pacra_teams.id
LIMIT 1
";
 // setting variable values during session

$_SESSION['og_users.username']=$username;
$_SESSION['pacra_teams.title']=$title;
?>

调用这些变量

<?php
session_start();
?>
<?php
print_r($_SESSION);
?>

请帮助我如何做到这一点?

一件事。如果我运行seesion.php页面它显示undefine变量“标题” 如果我运行打印代码。它显示用户名“root”,但我的数据库

中没有任何用户名root

2 个答案:

答案 0 :(得分:2)

您已经定义了一个查询,但没有执行它。

// starts session
session_start();
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "pacra1";

$conn = new mysqli($servername, $username, $password, $dbname);

$sql="SELECT *
FROM og_users
LEFT JOIN pacra_teams
ON og_users.id = pacra_teams.id
LIMIT 1
";
$result = $conn->query($sql);
$row = $result->fetch_object();
// setting variable values during session

$_SESSION['og_users.username'] = $row->USER_NAME; // Change to correct column name in table og_users
$_SESSION['pacra_teams.title'] = $row->TITLE_COLUMN_NAME; // Change to correct column name in table pacra_teams

答案 1 :(得分:0)

每次在sql语句中没有WHERE子句时,结果都是相同的。它只会返回它找到的第一行。看起来你正试图在会话变量中设置用户信息,这样你就可以在整个应用程序中调用数据,所以这里有一个可能的解决方案,假设你在某个地方获取用户ID(IE网页表单)。

这是解释概念的简单答案,而不是教程。

<?php

//Setup your connection stuff here
  session_start();
  $servername = "localhost";
  $username = "root";
  $password = "";
  $dbname = "pacra1";

//Get a user's name from a form
  $userName = $_POST['username'];

// Perform your query
  $db= new mysqli($servername, $username, $password, $dbname);
  $sql = "SELECT * 
  FROM og_users 
  LEFT JOIN pacra_teams 
  ON og_users.id = pacra_teams.id 
  WHERE og_users.username = {$userName} LIMIT 1";
  if(!$result = $db->query($sql)){
    die('Error [' . $db->error . ']');
  }

// Setting variable values during session
  while($row = $result->fetch_assoc()) {
    $_SESSION['ogUsername'] = $row['USERNAME']; // USERNAME is a placeholder for the example
    $_SESSION['pacraTeamsTitle'] = $row['TITLE']; // Same here
  }

这并不完美,但希望它有助于解释这个概念并帮助您完成任务。