在用户登录时检索并存储有关用户的其他信息

时间:2013-04-30 21:03:12

标签: php mysql

我有一个我正在使用的登录脚本,目前正在使用,但我想添加一些额外的功能,如显示名称,一些prefs等。我想在会话中存储用户ID,以便我可以使用它们导航网站进行查找,但我不知道如何去做。非常感谢任何帮助......代码如下。

<?php
include_once $_SERVER['DOCUMENT_ROOT'] .
'/includes/magicquotes.inc.php';

if (isset($_GET['login'])){
include 'login.html.php';
exit();
}

if (isset($_GET['security'])){
ob_start();
$host="localhost"; // Host name 
$username="*****"; // Mysql username 
$password="*****"; // Mysql password 
$db_name="*****"; // Database name 
$tbl_name="users"; // Table name 

// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect"); 
mysql_select_db("$db_name")or die("cannot select DB");

// Define $myusername and $mypassword 
$myusername=$_POST['myusername']; 
$mypassword=$_POST['mypassword']; 

// To protect MySQL injection (more detail about MySQL injection)
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'";
$result=mysql_query($sql);

// Mysql_num_row is counting table row
$count=mysql_num_rows($result);

// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1){

// Register $myusername, $mypassword and redirect home"
session_register("myusername");
session_register("mypassword"); 
header("location:/admin/");
}

else {
echo "Wrong Username or Password";
}
ob_end_flush();
exit();
}

if (isset($_GET['logout'])){
session_start();
session_destroy();
header("location:/admin/");
exit();
}   
session_start();
if(!session_is_registered(myusername)){
header("location:?login");
}

// Display Home Page

include $_SERVER['DOCUMENT_ROOT'] . '/includes/db.inc.php';

include 'home.html.php';
exit();

1 个答案:

答案 0 :(得分:1)

// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1){

// Register $myusername, $mypassword and redirect home"
session_register("myusername");
session_register("mypassword"); 
header("location:/admin/");
}

此处,在if语句中,您应该再次查询数据库,并选择要在会话中使用的名称等。

在if语句

中启动会话
// Register $myusername, $mypassword and redirect home"
$query = "SELECT `first_name` FROM `table` WHERE `username`=$username";
$result = $mysqli->query($query);
$row = $result->fetch_assoc();
$firstName = $row['first_name'];

session_start();
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
$_SESSION['firstName'] = $firstName;
header("location:/admin/");

显然我不知道你的数据库结构是什么样的,但我希望你明白这个想法

然后您在用户应登录的页面上启动会话,然后您可以通过

访问名字

e.g。

echo $_SESSION['firstName'];