我的表有两列,用户id和用户名。用户以如下用户名登录:

<?php

require('dbConnect.php');

$username = $_POST['username'];

//need to keep this in a session, for other pages later on
session_start();
    $_SESSION['username'] = $username;

$sql = "SELECT * FROM user WHERE username = '$username'";
$result = mysqli_query($con,$sql);

$check = mysqli_fetch_array($result);

if(isset($check)) :

//if the username exists in the database, then show a html submit button
$con->close();
?>
     <html>
<body>
<form action="UserDetails.php" method="post">
 <input type="submit">
</form>
     </html>

<?php  else :{
    //if user is not in db, show this message
         echo 'Sorry about that, you can't come in.';
     }
     $con->close();
 ?>
 <?php endif; ?>

如何获取对应于用户名的用户id,以便以后在页面中使用?

最佳答案

这里有几个问题:
1)如果您使用的是"SELECT * FROM user WHERE username = $1,那么username列应该是唯一的,并且不要忘记转义您的输入:

<?php
$username = mysqli_real_escape_string($con, $_POST['username']);
$sql_query = mysqli_query($con,"SELECT * FROM user WHERE username = '$username'");

2)您可以检查是否有任何结果b4任何东西,并直接从数据库分配这些变量。。。
if (mysqli_num_rows($sql) == 0) {
 $error = "This user doesn't exists here...";
}else{
  $user_info = mysqli_fetch_assoc($sql_query);
  $_SESSION['username'] = $user_info['username'];
  $_SESSION['user_id'] = $user_info['user_id'];

}

$con->close();
?>

然后,如果$_SESSION['user_id']确实存在,则可以为登录用户输出所需的任何内容。。。
<html>
 <body>
  <form action="UserDetails.php" method="post">
  <input type="submit">
  </form>
</body>

<?php
 echo 'Well, here\'s the output: <b>'. (isset($_SESSION['user_id']) ? $_SESSION['username'] : $error).'</b>';

关于php - 如何获取数据库中特定行的相应user_id(自动增量)值?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39778858/

10-13 23:04