tags:

views:

36

answers:

3

Im making a gaming community and i wanna be able to grab any info of the user on any page without so instead of having much of queries on all pages i made this function. Is it better to do this? Will this slow down the site?

/**
* Возьмем значение из любой области authed пользователей.
*/
function UserData($f)
{
    global $_SESSION;


    return mysql_result(mysql_query("SELECT `$f` FROM `users` WHERE `id` = ".intval($_SESSION['id'])), 0, $f);
}
+1  A: 

That function still adds a query to your page.

How about storing basic user info in a session or a cookie?

Haris
Yes after you login, save all data to $_SESSION[] variables.
Byron Whitlock
A: 

That's a little hard to decide from just the givens, but in general it depends on how you're using your function.

One famous technique is to load all the user data at the very top of your script and use that during your request. But if you're building an AJAX based application, which I'm guessing you are, that doesn't always help because most the data you're never going to use.

A good compromise would be to use a global variable with all user data for normal page requests, and on the other hand single attribute queries for AJAX requests and so forth.

Again it depends on your application. Rule of thumb: try to keep an eye on how often you "query" your database. PHP is usually faster than database queries so you'd rather keep queries to the minimum.

msakr
+2  A: 

$_SESSION is already a global, and is the right way to solve your issue.

The best for your need is to store the user data when he logs in, into an array, something like:

session_start();
// $mysql_data_row is the mysql row containing your user's data;

$_SESSION['user'] = $mysql_data_row;

And in each page, you'll have access to all the data stored in the session without having to query the database. For instance:

session_start();
echo 'hello ', $_SESSION['user']['name'];
pixeline