Christophe Harris Christophe Harris - 2 months ago 6
MySQL Question

How can I get the corresponding user_id (auto increment) value of a particular row in my database?

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 ?

Answer

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