Canada  united states of america usa  linkedinfacebook   Call Us Today: 866.646.6461

Accessing Joomla database (directly and indirectly)

There are various situations when you need to access the database in Joomla. The proper way of doing it is to use getDbo:

//-- Get a db connection --//
$db = JFactory::getDbo(); //-- Create a new query object --//
$query = $db->getQuery(true); //-- setup some query to execute --//
$query->select($db->quoteName(array('user_id', 'profile_key', 'profile_value', 'ordering')));
$query->where($db->quoteName('profile_key') . ' LIKE '. $db->quote('\'custom.%\''));
$query->order('ordering ASC');

//-- Execute the query --//
$db->setQuery($query); //-- save result in an array --//
$rows = $db->loadAssocList();

Of course if you want to do it the old-fashioned way, using direct PHP, you can do it like this:

//-- get joomla db config --//
$Config = new JConfig(); //-- then you can use these variables --//
$dbtype = $Config->dbtype; // Database driver name
$host = $Config->host; // Database host name
$user = $Config->user; // User for database authentication
$pass = $Config->password; // Password for database authentication
$dbname = $Config->db; // Database name
$prefix = $Config->dbprefix; // to use later in queries
//-- and do something silly like that --//
$conn = new mysqli($host, $user, $pass, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
//-- this is where you can use that $prefix, if you are selecting from Joomla DB directly --//
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);

ALT specializes in Web and Application development. Contact us and one of our specialists will be able to assist you.

Last updated Jun 26, 2019