Joshua
Joshua

Reputation: 119

PHP Query Database Using Session Information

I have been programming for a while but pretty new to PHP. I am have run into a problem. My site has a login/register screen and once logged into the account, I am trying to echo information from the users database entry. For example if I want to display the content "Balance" I have been trying the following code:

<?php 
    $data = mysql_query("SELECT * FROM users WHERE username=username") or die(mysql_error()); 
    while($info = mysql_fetch_array( $data )) 
    { 
        Print $info['balance']; 
    } 
?>

The idea is that the script will query the database using the username stored in the session then goto the named field.

When there is only one registered user, it appears to work, however; once multiple users enroll, it echoes the value from ALL users (ex. $7.50$10.12).

Thanks for your help in resolving this issue!

Upvotes: 0

Views: 281

Answers (1)

dev7
dev7

Reputation: 6369

Currently you are not comparing the username to a variable, but you are comparing it to itself, which means it will always be true.

<? 

$username = $_SESSION['username'];//or other methods like $_POST['username'] or $_GET['username'], depending on how you intend to get the username;

$data = mysql_query("SELECT * FROM users WHERE username='$username'") or die(mysql_error()); 

while($info = mysql_fetch_array( $data )) 
{ Print $info['balance']; }

 ?>

You neet to make sure the $username is escaped (if comes from user input) as well as start using mysqli or pdo instead of mysql.

And, of course, I'm assuming you are using session_start() somewhere and actually assigning the username to the session.

Hope this helps!

Upvotes: 4

Related Questions