且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-10-15 15:54:02

使用FETCH_ASSOC而不是FETCH_NUM


I need to input the USER_ID field of my USER table as a foreign key in another table. Therefore, I think I need to start a session when the user logs in. I'm having difficulty getting it to echo anywhere. I am able to start a session that allows me to echo the USERNAME, but cannot replicate it for the ID.

Any assistance please? My processing code is below. I have also pasted the section where I am temporarily trying to echo it for testing.

Processing script:

<?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();
}}

?>

Where I want the USER_ID to appear:

<?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>';
}
?>

use FETCH_ASSOC instead of FETCH_NUM