Okay, I'll explain by using a fictitious value.
You will need to reference the #__users
table and the #__fields_values
table.
Assuming you are only dealing with logged in users, you will need to acquire the user's id via JFactory::getUser()->id
.
Then you will need to know the field_id
that the gender
value is stored with in the #__fields_values
table. For my example below I'll use 28
as the field_id
value; if you don't know what the correct field_id
value is for your project, you can search for it in the #__fields
table the integer that you need to source is in the id
column.
By performing an INNER JOIN on the two tables, using two conditions in the WHERE clause and calling for a single value in the result set via loadResult()
, you shall have your gender
value.
try {
$db = JFactory::getDbo();
$user_id = JFactory::getUser()->id;
$query = $db->getQuery(true)
->select("b.value AS gender")
->from("#__users a")
->innerJoin("#__fields_values b ON a.id = b.item_id")
->where(["b.field_id = 28", "b.item_id = " . (int)$user_id]); // $user_id should already be an integer, but cast to be extra safe
$db->setQuery($query);
// JFactory::getApplication()->enqueueMessage($query->dump(), 'info');
if (!$gender = $db->loadResult()) {
echo "<p>No Value Found</p>";
} else {
echo "<p>$gender</p>";
}
} catch (Exception $e) {
JFactory::getApplication()->enqueueMessage("Query Syntax Error: " . $e->getMessage(), 'error'); // don't show $e->getMessage() to public
}
p.s. if you don't want to hardcode the "28" into your query, you can perform a dynamic lookup of the number, but that will require another JOIN with the #__fields
table -- this is not likely to worth the effort in most cases.
field_id
) value for your gender data in#__fields_values
?