MyBB Community Forums

Full Version: Get list of usernames from uid?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
In a plugin I made, I use a table with each row having 3 columns: uid, tid, and thirdcolumn (say).

Now if I do:
$query=$db->query("SELECT * FROM ".TABLE_PREFIX."plugintable WHERE tid='$tid'");
$record = $db->fetch_array($query);

Now that would definitely have multiple rows in my case. So how do I extract the list of uid's from $record and find out the corresponding usernames for those uids?
You can use a LEFT JOIN.

Based from your example, would be something like this:
$query=$db->query("SELECT u.username, p.* FROM ".TABLE_PREFIX."plugintable p, ".TABLE_PREFIX."users u LEFT JOIN (p.uid=u.uid) WHERE tid='$tid'");

while($record = $db->fetch_array($query)
{
  //Actions per row. Example:
  echo "The username for this result is: ".$record['username'];
}


Basically, LEFT JOIN will add the column 'username' from the users table, search the uid from the plugintable in the users table and returning the value of 'username' of that row.

Explaining that query, first I'm telling MySQL to select the field 'username' from the users table and all the columns from the plugintable, then compare the uid from both tables, but as we selected only the username field (first part of query), then the only additional field to be added to your results will be 'username'.