Log in

View Full Version : Working with fetch_arrow and queries



Scavenger
06-11-2010, 11:19 PM
Hello everyone!

This is my first post, I've been reading the forums and learning php & mysql for some time. I'm stuck with a doubt, I hope and appreciate if you can help me.

I'm running a web site using a database. To retrieve user's info I use:

$UsersQuery = mysql_query("SELECT * FROM users WHERE id=$id");

To get their usernames, registered date, etc. And I print that info with:

$user = mysql_fetch_assoc($UsersQuery)
$user['registered], etc

That works great, but when I want to retrieve who invited the user (invited_by, its an INT)

I tried something like $user['invited_by'], of course it will retrieve the INT of the inviter user (user id), but how can I make it to print the username of that inviter?

I can do something like

$invited_by = mysql_query("SELECT username FROM users WHERE id=$user[invited_by]");
$inviter = mysql_fetch_array($invited_by);

And I print it like:

$inviter['username']

But I'm using another query, I don't know if that's right because I already stored all the user's info in $user. Is there an easier way to do it?

Thanks for your help/time and excuse my noob question. :)

fileserverdirect
06-12-2010, 02:48 AM
Well, If you only stored the user-who-invited-the-current-user's UID number, and not their actual name, then there is no way that I can directly see you being able to get the user name. I'm not too big with SQL, some other forum users are more experienced, but logicaly in one query, it's not possible. You could set up an easy function which would save you time like:


function inviter(){
$invited_by = mysql_query("SELECT username FROM users WHERE id=$user['invited_by']");
return mysql_fetch_array($invited_by);
}

and call it directly after you MySQL:


$_GLOBALS['user'] = $user;
$inviter= inviter();

Not sure if it would really make it any more streamline, but if you needed to do multiple users, a function would be the best way to go.

djr33
06-12-2010, 04:58 AM
I'd suggest a single function called getuserinfo($id). You can embed this in itself if you want or just call it twice.

fileserverdirect
06-12-2010, 08:19 PM
Basically this could be done in one function, and it would save time:


function getUserInfo($id){
$UsersQuery = mysql_query("SELECT * FROM users WHERE id=$id");
$user = mysql_fetch_assoc($UsersQuery);
$invited_by = mysql_query("SELECT username FROM users WHERE id=$user['invited_by']");
$user['invited_by_name'] = mysql_fetch_array($invited_by);
return $user;
}

To use the name of the person who invited the current user, use:


$user= getUserInfo($_SESSION['id']); // where $_SESSION['id'] is set from login.
echo $user['invited_by_name']; // displays the inviter's name.