如何获取数据库中特定行的相应user_id(自动增量)值?

时间:2016-09-29 19:52:39

标签: php mysql

我的表有2列,user_id和username。用户使用以下用户名登录:

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

如何获取与用户名相对应的user_id,以便稍后在页面中使用?

4 个答案:

答案 0 :(得分:2)

这里有一些问题:

1)如果您使用的是"SELECT * FROM user WHERE username = $1,那么用户名列应该是 UNIQUE ,并且永远不会忘记逃避您的输入:

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

答案 1 :(得分:1)

在以下几行之后:

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

添加以下行:

$row = mysqli_fetch_assoc($result);
$user_id = $row["user_id"];

答案 2 :(得分:0)

isset($check)此时不保存,更好地检查$ check的值以及{}之后else不需要它,它将无效。

答案 3 :(得分:0)

(isset($check))似乎给我带来了麻烦,有时会返回user_id,有时不会。{/ p>

在很大程度上要归功于Nabeel的回答,这个想法对我有用。还要感谢Solrac Ragnarockradio使我能够通过mysqli_real_escape_string让我的代码更安全:

<?php
require('dbConnect.php');

$username = mysqli_real_escape_string($con,$_POST['username']);

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

$row = mysqli_fetch_assoc($result);
$user_id = $row["user_id"];

//give me the corresponding user_id of the logged in user
echo $user_id;

if (mysqli_num_rows($result)==0) {
    echo "Failed, sorry";
}

if (mysqli_num_rows($result) > 0) {
    echo "User id exists already.";

    }

$con->close();
?>