dongqiongzheng0615 2016-09-29 19:52
浏览 132
已采纳

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

My table has 2 columns, user_id and username. The user logs in with username like this :

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

How can I get the user_id that corresponds to username, to be used in pages later on ?

  • 写回答

4条回答 默认 最新

  • doulu4976 2016-09-30 23:45
    关注

    The (isset($check)) seemed to be causing me trouble, sometimes returning user_id, sometimes not.

    Thanks in large part to Nabeel's answer, this idea worked for me. And also thanks to Solrac Ragnarockradio for putting me on track to make my code more secure with 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();
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应