我需要输入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>'; } ?>
使用FETCH_ASSOC而不是FETCH_NUM