I’m currently working on a user authentication script for a web game and after the user logs in I want to have a little user area where it shows how much currency the player currently has. I was thinking I could just do a select query like select * from users where username = $_SESSION[‘username’] and then use fetch array to display the amount of currency the user has but it doesn’t seem like you can use variable names directly in a query or can you?
You can, but you shouldn’t for what you are doing. When someone logs in, you should store the user’s id (auto-increment primary index) from the user’s table in the session variable. There are two reasons for this - 1) it will result in the fastest query, and 2) it will allow the username to be edited using the simplest code.
You should also be using a prepared query when supplying a dynamic value to the query when it gets executed, not by putting the value directly into the sql query statement…
So how would I write it searching the users table by ID instead of username and then displaying how much currency have?
After reading more closely what you are doing, any real, virtual, or token based currency should be kept track of in an ACCOUNTing table, with a user_id column to relate the rows back to the user, with one row inserted for each transaction that adds or subtracts an amount, just like a bank or credit card account would do.
To get the current total for any user, you would use a SELECT query with a SUM(amount) term in it.