2

I have the following code in an article using Sourcerer and it works fine but I would like to move the connection section out of the function so that I only need to create it once for multiple functions but I'm struggling to make it work. Outside Joomla I would have just called it as global $option or $db but neither work.

Working code:

    function getclientstock($client) {


$option=array();
$option['driver']   = 'mysql';            // Database driver name
$option['host']     = 'localhost';    // Database host name
$option['user']     = 'user';       // User for database authentication
$option['password'] = 'pass';   // Password for database authentication
$option['database'] = 'database';      // Database name
$option['prefix']   = '';             // Database prefix (may be empty)
$db=JDatabaseDriver::getInstance($option);

    $query=$db->getQuery(true);
    $query->select($db->quoteName(array('unit_imei' , 'client')));
    $query->from($db->quoteName('connections'));
    $query->where($db->quoteName('client') . ' = ' . $db->quote($client));
    $db->setQuery($query);
    $result=$db->loadAssocList();
    return $result;
};
1

If you are doing multiple function all on the same page you could setup the database connection and then pass it to the different functions.

Take a look at this answer on Stack OverFlow: https://stackoverflow.com/questions/11492285/the-correct-way-to-include-connection-using-mysqli

<?php 
    $option=array();
    $option['driver']   = 'mysql';            // Database driver name
    $option['host']     = 'localhost';    // Database host name
    $option['user']     = 'user';       // User for database authentication
    $option['password'] = 'pass';   // Password for database authentication
    $option['database'] = 'database';      // Database name
    $option['prefix']   = '';             // Database prefix (may be empty)
    $db=JDatabaseDriver::getInstance($option);   

    function getclientstock($db, $client) {

        $query=$db->getQuery(true);
        $query->select($db->quoteName(array('unit_imei' , 'client')));
        $query->from($db->quoteName('connections'));
        $query->where($db->quoteName('client') . ' = ' . $db->quote($client));
        $db->setQuery($query);
        $result=$db->loadAssocList();
        return $result;
    };

    function setclientstock($db, $client) {
      // code here...

    };

?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.