Why?
I'm building a Joomla component which is to be compatible with Joomla versions 1.6.x to 2.5.x. Because I use dynamic scripts running in the background (mootools), some of these need to connect to the database but as they sit outside of the MVC structure, we need them to use the existing configuration file in order to retrieve the credentials (ie. username, password, database, etc.). For obvious reasons, these cannot be hardcoded.
What?
Any developer installing my component will do so on a website which uses different login details for their Joomla database. The example below demonstrates how to get these details and extract data from the database.
How?
Based on a script I found on StackOverflow. Not sure what version they were using so I modified it to make this work with my environment (Joomla 2.5.6). This is a cut down version of my download.php script:
//init Joomla Framework
define( '_JEXEC', 1 );
define( 'JPATH_BASE', realpath(dirname(__FILE__).'/../..' )); // print this out or observe errors to see which directory you should be in (this is two subfolders in)
define( 'DS', DIRECTORY_SEPARATOR );
require_once ( JPATH_BASE .DS.'includes'.DS.'defines.php' );
require_once ( JPATH_BASE .DS.'includes'.DS.'framework.php' );
require_once ( JPATH_CONFIGURATION .DS.'configuration.php' );
require_once ( JPATH_LIBRARIES .DS.'joomla'.DS.'database'.DS.'database.php' );
require_once ( JPATH_LIBRARIES .DS.'import.php' );
//DB Connection
$Config = new JConfig();
$db_driver = $Config->dbtype; // Database driver name
$db_host = $Config->host; // Database host name
$db_user = $Config->user; // User for database authentication
$db_pass = $Config->password; // Password for database authentication
$db_name = $Config->db; // Database name
$db_prefix = $Config->dbprefix; // Database prefix (may be empty)
// Database prefix (if empty then remove prefixing double underscore)
$db_prefix = (trim($db_prefix)=="") ? "":$db_prefix;
$db_connect = mysqli_connect($db_host,$db_user,$db_pass);
$content_count = 0;
// CONNECTED! so run a SQL query as per usual
if (!mysqli_connect_errno()) {
$query='SELECT COUNT(*) as ArticleCount FROM `'.$db_prefix.'content` WHERE id='.mysqli_real_escape_string($db_connect, $_GET['id']);
if ($result = mysqli_query($db_connect, $query, MYSQLI_USE_RESULT)) {
while($obj = $result->fetch_object()){
$content_count = $obj->ArticleCount;
}
}
}
echo $content_count;
mysqli_free_result( $db_connect );
Clear as mud? Feel free to use the comment fields at the bottom of this page to ask a question.Additional
I'm pretty sure you don't need all the require files and my solution may be crude, but this script works perfectly for what I had in mind.
Important!
There are a few concealed features of this script that I haven't made a song and dance about but are noteworthy:
- The only anti-code injection facility in this example is the "mysqli_real_escape_string" function applied to a number. You will need to be more vigilent.
- Variables are all cleared and redefined. To pass a value to this script you have to use the $_GET, $_POST or $_SESSION methods. Or redeclare it after the above.
- MYSQLI_USE_RESULT allows these results to be used once, remove it if you need counts or to use the data later on.
Further Post-Joomla 2.5 aides
- Validating a login was MD5(password+salt) but is expected to be (not tested)
bool correctPass = CryptSharp.PhpassCrypter.CheckPassword(passwordPlain, joomlaPassword);
Very helpful tips to know how to Connect to Joomla database in standalone script. Thanks for sharing this info. As am a joomla beginner, I found this post interesting and I could able to learn many new stuffs in your blog. Thanks. Keep updating information to resolve any errors or tutorials.
Hi Freemac,
I haven't seen that one before. Shouldn't it be using password:YES? The root@localhost sounds like a default. Maybe it's a matter of specifying the path to the configuration file rather. Apologies as I haven't replicated this error so not 100% sure.
Thanks for the comment though!
Hi Feemac,
Check the line [code]realpath(dirname(__FILE__).'/../..' )[/code] as this is the location of your configuration file.
Yes I discovered issues when using this script where I've defined a variable before the script (so eg. $FileID=$_GET['id']*1) and then trying to use $FileID after connecting to the database). What seems to happen are the variables get cleared. You need to (re)define any variables after the "DB Connection" section.
Also note that this script doesn't use normal Joomla Database commands and instead uses normal mySQL/PHP database commands.
Hope that helps!
Hi Joel, This is what I've been looking for! Just wondering though, why would I be getting the error "Access denied for user 'root'@'localhost' (using password: NO)" when that isn't even the user and password I've provided in the variables?