1. NOTICE: If you are using Fabrik and update to Joomla 3.10, you will need to update to Fabrik 3.10. And, if you are using Fabrik, do not upgrade to Joomla 4, we do not have a supported version ready for release. More information on a release date coming soon. Also, please note that Fabrik 3.10 will not install on any Joomla sites less than 3.8.
    Dismiss Notice

PHP common tasks

Apr 7, 2021
PHP common tasks

  • Standard Evaluations (top)

    Using eval
    Element_default_examples

    Forms (top)

    Form submission

    Databases (top)

    Joomla.25/Joomla3 syntax see http://docs.joomla.org/Accessing_the_database_using_JDatabase

    Examples:(top)


    Select (top)


    Load an array of rows as objects:
    PHP:
    // Get a db connection.
    $myDb = JFactory::getDbo();

    // Create a new query object.
    $myQuery = $myDb->getQuery(true);

    $myQuery
        ->select(array('fieldA', 'fieldB'))
        ->from('tablename')
        ->where('fieldC = ' . $myDb->quote('value'));

    // Assign the query to the db
    $myDb->setQuery($myQuery);

    // Load the results as an array of objects.
    $rows = $myDb->loadObjectList();
    Returning data from the array of rows (above) and display it
    e.g when using a calc element for this purpose? Let's say we want to display the rows as fieldA and fieldB in an ordered list:
    PHP:
    $list = array();
    foreach ($rows as $row)
    {
        $list[] = "<li>" . $row->fieldA . " " . $row->fieldB . "</li>";
    }
    return "<ol>" . implode($list) . "</ol>";
    Load a single ROW of data as an object:
    PHP:
    $myDb = JFactory::getDbo();
    $myQuery = $myDb->getQuery(true);

    $myQuery
        ->select(array('fieldA', 'fieldB'))
        ->from('tablename')
        ->where('fieldC = ' . $myDb->quote('value'));

    $myDb->setQuery($myQuery);

    $row = $myDb->LoadObject();
    Note: In additional to loading by table name, if you know the $id of the record you wish and want to load it from the list name (instead of table name), you can use the Fabrik List Model like this...

    PHP:

    $row = $listModel->getRow($rowId);


    Load a single VALUE from a ROW of data:
    PHP:
    $myDb = JFactory::getDbo();
    $myQuery = $myDb->getQuery(true);

    $myQuery
        ->select('fieldA')
        ->from('tablename')
        ->where('fieldC = ' . $myDb->quote('value'));

    $myDb->setQuery($myQuery);
    $fieldA = $myDb->loadResult();
    Note: loading a single row is often used to populate a field with some default data - if you are using eval on a field you should return the value as per this line of code:
    PHP:
    return $fieldA;
    See using eval for more info

    Insert (top)


    Insert data into a database:
    PHP:
    // Get a db connection.
    $myDb = JFactory::getDbo();

    // Create a new query object.
    $myQuery = $myDb->getQuery(true);

    // Insert columns.
    $columns = array('fieldA', 'FieldB');

    // Insert values.
    $values = array('1', '2');

    // Prepare the insert query.
    $myQuery
        ->insert($myDb->quoteName('tablename'))
        ->columns($myDb->quoteName($columns))
        ->values(implode(',', $myDb->quote($values)));

    // Reset the query using our newly populated query object.
    $myDb->setQuery($myQuery);

    try {
    // Execute the query
      $result = $myDb->execute();
    //use $myDb->query() in Joomla2.5
    }
    catch (Exception $e) {
    // catch any database errors.

    }
    $newid = (int)$myDb->insertid(); //get new record id
     

    Update (top)

    Update a table with a join (use another field [Status] instead of it's ID value):
    PHP:
    $IDinput = '{rowid}';

    // Get the db object
    $myDb = JFactory::getDbo();

    // Build the query ? Tables names = CASE SENSITIVE
    $myQuery = $myDb->getQuery(true);

    $myQuery
          -> update('contacts AS c')
          -> join('INNER','contactsstatus AS s ON s.Status = \'New\'')
          -> set('c.Status = s.id')
          -> where('c.id = '. (int) $IDinput);

    $myDb->setQuery($myQuery);

    // Run the query
    $found = (int) $myDb->execute();
    //use $myDb->query() in Joomla2.5

    Use alternate Fabrik connection (top)


    Here we are loading the connection with an ID of 2:
    PHP:
    $myDb = FabrikWorker::getDbo(false, 2);

    Get A List's data (top)


    For Fabrik 3.0+, to get data from a List with an ID of 1:
    PHP:

    // Fabrik 3.1
    $listModel = JModelLegacy::getInstance('List', 'FabrikFEModel');

    // Fabrik 3.0
    $listModel = JModel::getInstance('List', 'FabrikFEModel');

    $listModel->setId(1);
    $data = $listModel->getData();

    // Get params
    $params = $listModel->getParams();
     
    If you want to access the list from a external script, you'll need to include the model by adding this line to your script prior to the the above:
    PHP:

    JModel::addIncludePath(JPATH_SITE . '/components/com_fabrik/models');
    And to read a record from a List when knowing the row's $id:
    PHP:

    $row = $listModel->getRow($rowid);

    Users (top)


    To get the current, logged-in user in Joomla you need this line:
    PHP:
    $user = JFactory::getUser();
    To grab a property from the user object:
    PHP:
    $userid = $user->get('id');
    $name = $user->get('name');
    $username = $user->get('username');
    $email = $user->get('email');
    To grab all user's groups you need this line :
    infos in an array and the "false" option remove default joomla groups( like admin or register...)
    PHP:
    $groups = JAccess::getGroupsByUser({$my->id}, false);
    return($groups);
    To grab a specifique user's group you need to return something like :
    PHP:
    $groups = JAccess::getGroupsByUser({$my->id}, false);
    return($groups['3']);

    URL parameters (top)

    If your URL is something like ...&urlparam=abc...
    PHP:
    $myApp = JFactory::getApplication();
    $myparam= $myApp->input->get('urlparam');
     
    See also https://docs.joomla.org/Retrieving_request_data_using_JInput

    Dates (top)


    Deciding in PHP if a date within an age range
    To check someone's age from their date of birth:

    PHP:
    $myApp = JFactory::getApplication();
    $date= $myApp->input->getString('tablename___dateelement');
    $date = strtotime($date);
    $now = time();
    $diff = $now - $date;
    $years = floor($diff / 31556926);
    return ($years >= 18 && $years <= 90);
    Difference in days between 2 dates in PHP
    This gives the difference in days between a date element and today, Alternatively you could swap 'today' with another date or field

    PHP:
    $nowdate = strtotime("{table___element}");
    $thendate = strtotime("today");
    $datediff = ($thendate - $nowdate);
    $diff = round($datediff / 86400);
    return $diff;
    It was used in a schedule task email plugin that required multiple conditions to be met, as follows

    PHP:
    $cond1 = ('{table___element}' == 'X');
    $nowdate = strtotime("{table___element}");
    $thendate = strtotime("today");
    $datediff = ($thendate - $nowdate);
    $diff = round($datediff / 86400);
    $cond2 = ($diff == X);
    return $cond1 <> $cond2;
    Send a reminder email only to the rows(users) that didn't update a record for more than 16 days.

    PHP:
    $date1 = strtotime("{table___update_raw}");
    $date2 = strtotime("{table___createdate_raw}");
    $date2 = strtotime("+16 day", $date2);
    return $date1 > $date2;
    To translate any dates in your own language on the fly, starting with MariaDB 10.3.8, there is now a third argument possible in your date_format function query.
    Here is an example of a date translated in french right in a query using a calc element:

    PHP:
    $query->setQuery('SELECT date_format(date, "%d %M %Y", "fr_FR") as frenchdate FROM table_name WHERE my_condition = X');
    So as always, you give the date_format function the 2 first argument (the date you want to display, followed by the way you want it to display)... but now you can add a third argument telling which language you want your date to display. It's Magic !

    Filtering a database join element's filter drop-down values to only those values from the joined table for which the user is authorized(top)


    If you have enabled filtering for a database join element, and the element joins a list that has an element that stores the Joomla view-level that is allowed to see that record, then you can filter the values presented in the database join element's filter drop down values to remove joined records from the filter drop-down values where a joined record does not contain a view_level for which the current logged in user is authorized to view.

    Code (Text):

    {thistable}.view_level IN (SELECT DISTINCT `#__viewlevels`.`id`
    FROM #__user_usergroup_map
    LEFT JOIN #__viewlevels ON REPLACE(REPLACE(rules,'[',','),']',',') LIKE CONCAT('%,',`group_id`,',%')
    WHERE user_id ='{$my->id}')
     
    In the example above, the query referenced the Joomla viewlevels table and the joomla user_usergroup_map table to work-out the viewlevels that the user is authorized to see. The database join in this example populates it drop-down values from the element called 'view_level' ({thistable}.view_level). The query uses that value to determine if the current logged in user is authorized for the view level id stored in that element of the joined record.
Nagtegaal, louis037, samani and 12 others like this.