0

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!

1
  • username=username = always true. Do add the username from the session, you are now comparing a column with itself. Commented Jan 25, 2014 at 1:59

1 Answer 1

4

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!

Sign up to request clarification or add additional context in comments.

5 Comments

Beat me to it :) Good answer
@Yani Wow! Fast, concise, and most importantly, it worked! Thanks a ton.
@user3234098 Glad to help! It's with the help of all the caffeine I had today!
@Yani That must be some good caffeine. I need to get my hands on that for my next long programming session. Follow-on question, is there any benefit to dimming the variable ahead of time instead of just: ("SELECT * FROM users WHERE username='{$_SESSION['username']}'") Thanks, again!
Some would say that it's not the caffeine but how you make it. Technically yes, you want to both validate it and escape it unless you are 100% sure it exists and valid. Then you can use it directly from the session array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.