当用户使用用户名和用户登录时获取用户ID密码

时间:2014-01-13 16:11:06

标签: php html mysql sql

我需要在另一个表中输入USER表的USER_ID字段作为外键。 因此,我认为我需要在用户登录时启动会话。我很难让它在任何地方回显。我能够启动一个允许我回显USERNAME的会话,但不能复制它作为ID。

请帮忙吗?我的处理代码如下。我还粘贴了我暂时试图回应它以进行测试的部分。

处理脚本:

<?php
session_start();
$error_message = array();
$error = false;
$dbhost     = "localhost";
$dbname     = "xxx";
$dbuser     = "xxx";
$dbpass     = "xxx";

$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);

$user = $_POST['uname'];
$password = $_POST['pword'];  

if($user == '') {
    $error_message[] = 'You have not entered the required username.';
    $error = true;
}
if($password == '') {
    $error_message[] = 'You have not entered the required username';
    $error = true;
}

$result = $conn->prepare("SELECT * FROM USER WHERE USERNAME= :un AND PASSWORD= :pw");
$result->bindParam(':un', $user);
$result->bindParam(':pw', $password);
$result->execute();

while ($rows = $result->fetch(PDO::FETCH_NUM)) {



if($rows > 0) {

$_SESSION['Logged_In'] = true;
$_SESSION['username'] = $user; 
$_SESSION['USER_ID'] = $rows['USER_ID'];
header('Location: index.php');
}

else{

    $error_message[] = 'Your username and password are not correct. Try again.'; 
    $error = true;
}

if($error) {
    $_SESSION['ERROR_MESSAGE'] = $error_message;
    session_write_close();
    header("location: log_in.php");
    exit();
}}

?>

我希望USER_ID出现在哪里:

<?php
         session_start();
         if(isset($_SESSION['Logged_In']))
{
    echo '<br><br>';
    echo 'You are logged in as ';
    echo $_SESSION['username'];
    echo '<br>';
    echo "ID = ".$_SESSION['USER_ID'];
    echo '<br>';
    echo '<a href="logout.php">
Click here to log out.</a>';
}
else
{   
    echo '<br>';
    echo 'You are not logged in!<br>';
    echo '<a href="log_in.php">Click here to log in,</a><br>';
    echo '<a href="register.php">or click here to register.</a>';
}
?>

1 个答案:

答案 0 :(得分:0)

使用FETCH_ASSOC而不是FETCH_NUM

相关问题