CMS Development Joomla

External Login Script and getDbo()

I have a Joomla 3.9.14 site with a subdomain I have a login form, and I want to allow users to login using their Joomla credentials.

Everything is working as expected, users are able to login and authenticate successfully, however I need help with a function. I want to be sure I’m doing things correctly before proceeding.

My understanding was that I setup a connection to my Joomla database using $db = JFactory::getDbo(); and this would allow me to run queries throughout my site.

I have included the Joomla connection in a conn.php file, but it seems I also have to include $db = JFactory::getDbo(); within each of my functions – is this correct?

I have three files, see below for current code;


    define('_JEXEC', 1);    
    define('JPATH_BASE', realpath(dirname(__FILE__) . '/..'));
    require_once JPATH_BASE . '/includes/defines.php';
    require_once JPATH_BASE . '/includes/framework.php';

    $app   = JFactory::getApplication('site');
    $db     = JFactory::getDbo(); 




  if(isset($_POST['username']) && isset($_POST['password'])) {

      $username = trim($_POST['username']);
      $password = trim($_POST['password']);
      // do user login
      userLogin($username, $password);


  <form method="POST">
      <input type="text" name="username">
      <input type="password" name="password">
    <button type="submit">Sign in</button>



function userLogin($username, $password) {

    // only works if I include this line within the function
    $db = JFactory::getDbo();

    $credentials['username'] = trim($_POST['username']);
    $credentials['password'] = trim($_POST['password']);

    if(class_exists(JFactory)) {

        $query  = $db->getQuery(true);

        $query->select('id, password');
        $query->where('username=' . $db->quote($credentials['username']));

        $result = $db->loadObject();

        if ($result)
            $match = JUserHelper::verifyPassword($credentials['password'], $result->password, $result->id);

            if ($match === true)
                $user = JUser::getInstance($result->id); // Bring this in line with the rest of the system

                echo ("This user is logged in and Joomla also logged in! ");
                echo ("User name and password not match! ");
            echo ("THE USER IS NOT REGISTERED! ");


In the user.php file, if I move $db = JFactory::getDbo(); outside of the function I get this error message;

0 Call to a member function getQuery() on null

Do I just keep this line in each function or should I be including / calling it somewhere else?

Leave a Reply

Your email address will not be published. Required fields are marked *