Common PHP tasks

  • Views Views: 74,730
  • Last updated Last updated:
  • Standard Evaluations​

    Using eval
    Element_default_examples

    Forms​

    Form submission

    Databases​

    https://docs.joomla.org/Special:MyLanguage/J4.x:Selecting_data_using_JDatabase
    https://docs.joomla.org/J4.x:Inserting_Updating_and_Removing_data_using_JDatabase

    Examples:​


    Select​


    Joomla 4: Get a Database Object
    PHP:
    $myDb = Factory::getContainer()->get('DatabaseDriver');

    Joomla 4: Load an array of rows as objects:
    PHP:
    // Get a db connection.
    $myDb = Factory::getContainer()->get('DatabaseDriver');

    // 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();

    Joomla 4: Load an array of rows as objects:
    PHP:
    // Get a db connection.
    $myDb = version_compare(\Joomla\CMS\Version::MAJOR_VERSION, "4", ">=") ? Factory::getContainer()->get('DatabaseDriver') : Factory::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();



    Joomla 3: 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>";

    Joomla 4: Load a single ROW of data as an object:
    PHP:
    $myDb = version_compare(\Joomla\CMS\Version::MAJOR_VERSION, "4", ">=") ? Factory::getContainer()->get('DatabaseDriver') : Factory::getDbo();
    $myQuery = $myDb->getQuery(true);

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

    $myDb->setQuery($myQuery);

    $row = $myDb->LoadObject();


    Joomla 3: 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​


    Insert data into a database:
    PHP:
    // Get a db connection.
    $myDb = version_compare(\Joomla\CMS\Version::MAJOR_VERSION, "4", ">=") ? Factory::getContainer()->get('DatabaseDriver') : Factory::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​

    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();// for Joomla 3

    $myDb = version_compare(\Joomla\CMS\Version::MAJOR_VERSION, "4", ">=") ? Factory::getContainer()->get('DatabaseDriver') : Factory::getDbo();// for Joomla 4+

    // 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​


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

    Get A List's data​


    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​


    Joomla 4: To get the current, logged-in user in Joomla you need this line:
    PHP:
    $user = Joomla\CMS\Factory::getApplication()->getIdentity();

    Joomla 3: To get the current, logged-in user in Joomla you need this line:
    PHP:
    $user = JFactory::getUser();
    $email = $user->get('email');[/PHP]


    Joomla 4 & 3: 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');

    Joomla 4: To grab the current logged in user's Joomla user custom fields
    PHP:

    use Joomla\CMS\Factory;
    $user = \Joomla\CMS\Factory::getApplication()->getSession()->get('user');
    $customFields = FieldsHelper::getFields('com_users.user', $user, 0);
    foreach ($customFields as $field) {
    echo '$field=' . $field->name . '<br>';
    echo '$value=' . $field->value . '<br>';
    echo '<br>--<br>';
    }


    Joomla 4: To grab all user's groups you need:
    PHP:
    $user = Joomla\CMS\Factory::getApplication()->getIdentity();
    $Groups = $user->getAuthorisedGroups();

    Joomla 4: To grab all user's authorized view levels you need :
    PHP:
    $user = Joomla\CMS\Factory::getApplication()->getIdentity();
    $myViewLevels = $user->getAuthorisedViewLevels();

    Joomla 3: 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);

    Joomla 3: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​

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

    Dates​


    Deciding in PHP if a date within an age range
    To check someone's age from their date of birth:
    //not tested for Joomla 4
    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​


    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:

    {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.

    Mailing via php hooks​

    There are Joomla and Fabrik helpers for mailing, e.g. https://docs.joomla.org/Sending_email_from_extensions
    or Fabrik
    Code:
        /**
    * Function to send an email
    *
    * @param string $from From email address
    * @param string $fromName From name
    * @param mixed $recipient Recipient email address(es)
    * @param string $subject email subject
    * @param string $body Message body
    * @param boolean $mode false = plain text, true = HTML
    * @param mixed $cc CC email address(es)
    * @param mixed $bcc BCC email address(es)
    * @param mixed $attachment Attachment file name(s)
    * @param mixed $replyTo Reply to email address(es)
    * @param mixed $replyToName Reply to name(s)
    * @param array $headers Optional custom headers, assoc array keyed by header name
    *
    * @return boolean True on success
    *
    * @since 11.1
    */
    public static function sendMail($from, $fromName, $recipient, $subject, $body, $mode = false,
    $cc = null, $bcc = null, $attachment = null, $replyTo = null, $replyToName = null, $headers = array())
Back
Top