我正在尝试在用户登录后显示用户名。他们使用他们的电子邮件和密码登录虽然,我想收集他们的名字并显示它。它们的名称与电子邮件/密码所在的表相同。传统上,我会使用如下所示的会话ID。
<?php
session_start();
$_SESSION['first'] = $first;
?>
但这通常用于表单中提交的数据,并在表单经过身份验证后使用。我的问题是,如何从mySQl表中收集数据而不是从表单中收集数据并且能够让它具有会话ID?...如果这有意义
答案 0 :(得分:0)
在检查用户名和密码匹配时选择名字(以及您想要的任何其他字段)。
if (!isset($_SESSION)) session_start();
$sql=sprintf("SELECT email, firstname FROM users WHERE email=%s AND password=%s",
$_POST["email"], $_POST["password"]);
//You'd better use parameterized query
$result = mysqli->query($sql);
$row = $result->fetch_assoc();
if(mysqli->num_rows > 0)
{
$_SESSION["email"] = $row["email"];
$_SESSION["firstname"] = $row["firstname"];
}
else
{
//operation for no matches
}
答案 1 :(得分:0)
在他们登录的脚本中......只需获取行并存储到会话中......
我正在使用PDO,因为这比您在登录示例中使用的已弃用的mysql_ *函数更安全.......
//start the session
session_start();
//Get their credentials, as follows...
$name = $_POST['username'];
$pass = md5($_POST['password']);
$stmt = $db->prepare("SELECT * FROM admin WHERE username=? AND password=?");
$stmt->execute(array($name, $pass));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if($row > 0 ) {
//Store users info in a session
$_SESSION["username"] = $row["username"];
$_SESSION["firstname"] = $row["firstname"];
$_SESSION["auth"] = "set";
//Redirect to the user area, where you can echo their name
header ("Location: /app");
//Once in the user area, you can just echo their name like so...
//echo "Hello ".$_SESSION['username'].", Welcome to my site";
} else {
//Redirect back to login if their info is incorrect
header('location: /login');
//whatever your login page name might be...
}
但如果您不想更改您的网站以使用PDO,请继续使用代码......
include("db.php");
session_start();
if($_SERVER["REQUEST_METHOD"] == "POST")
{
$username=mysql_real_escape_string($_POST['username']);
$password=md5(mysql_real_escape_string($_POST['password']));
$sql="SELECT id, username, firstname FROM admin WHERE username='$username' and passcode='$password'";
$result=mysql_query($sql);
$row = mysql_fetch_row($result);
if(count($row)>0)
{
$_SESSION['auth'] = 'set';
$_SESSION['username'] = $row['username'];
$_SESSION['firstname'] = $row['firstname'];
header ("Location: /app");
}
else
{
$error="Your Hngout credentials are incorrect";
}
}