How can i display my current logged in users Info (PHP AND MYSQL)

Trying to show the currently logged in users data ie; username , user id and date the acc was created

Example screenshot https://jxb.pw/u/idqg.png

Trying to use <?php echo $_SESSION["id"] ?>

  $sql_query = "select ID,username from users where username like '$username' and password like '$password';";
$result = mysqli_query($conn, $sql_query);

if(mysqli_num_rows($result) > 0 ){

$row = mysqli_fetch_assoc($result);
$name = $row["username"]; 
$user_id =  $row['ID'];
echo $user_id;
$_SESSION["id"]=$user_id;

Assuming the code you pasted here is the login code and that you begin both your login php file and your other php file with session_start() and you have a column called ID (why uppercase?) it would seem this should work. Do you get any errors?

Hopefully once you have this working you will change to store a hashed password in the database instead of just selecting by username and password.

What you should really be concerned with is the gaping SQL Injection attack that your code is vulnerable to. NEVER EVER put variables in a query. Use Prepared Statements. And for gawd sake, stop using plain text passwords and stop creating variables for nothing.

this is my dashboard.php what im trying to do is get a users id after they login and display it on the user info part of the dashboard

So what exactly happens when you run this? Do you get an error message? Do you get a blank page? Does it output a value you don’t expect? Does it output nothing at all? Is this just a snippet of the code, and is there other markup around it, or is this the whole dashboard.php file?

Need a bit more information about the context to give more specific advice.

Overall though, you have a few issues here with security. The most important being that you have a pretty big sql injection vulnerability here (probably, this looks like just a snippet so perhaps you sanitize your variables in a different part of the code).

I’m also curious why you use like rather than an equality check. Is that just the new way of doing things in PHP? Like is generally a pretty resource intensive check so it seems like your doing an inefficient check for no real benefit. Maybe your just following a tutorial and the reasoning is there? I haven’t written raw PHP in a while (everyone uses frameworks no a days) so maybe this is just the new way of doing things.

You also doing have a closing curly bracket to that if statement. I’m assuming that’s because the code above is just a snippet, and you forgot to copy that part of it, but if not you can try adding that closing curly bracket and see if that helps.

Sponsor our Newsletter | Privacy Policy | Terms of Service