Im currently writing a script which will be run as a cronjob to do some calculations using values out of the joomla database, Because this script is not going to be accessed via joomla as a plugin etc i need to do DB connections with it.
What im attempting to do is use the Joomla framework to do all the work(Connection, queries, etc) for security and also portability purposes (instead of having another set of the login credentials in this script its all handled by the Joomla config)
I have done the best i can but when i run the script i get the following error:
Database Error: Unable to connect to the database:Could not connect to MySQL
I have printed out the variable and made sure that the connection details for mysql are correct (which they are).
My Current Code is:
<?php
//init Joomla Framework
define( '_JEXEC', 1 );
define( 'JPATH_BASE', realpath(dirname(__FILE__).'/..' ));
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_BASE .DS.'includes'.DS.'database.php' );
require_once ( JPATH_LIBRARIES .DS.'joomla'.DS.'import.php' );
//DB Connection
$Config = new JConfig();
$option['driver'] = $Config->dbtype; // Database driver name
$option['host'] = $Config->host; // Database host name
$option['user'] = $Config->user; // User for database authentication
$option['password'] = $Config->password; // Password for database authentication
$option['database'] = $Config->db; // Database name
$option['prefix'] = $Config->dbprefix; // Database prefix (may be empty)
$db = & JDatabase::getInstance($option);
//DBQuery
$database =& JFactory::getDBO();
$query = "SELECT * FROM #__chronoforms_RD_NonDangerousGoods WHERE cf_id = 4;";
$database->setQuery($query);
$result = $database->query();
print_r($result);
?>
try this
To fix "query" deprecation warning use
JDatabaseDriver
insteadJDatabase
:This works for Joomla 2.5 (and 3.5)
EDIT: The goal here is to connect to database using already set up Joomla configuration and execute SQL queries with Joomla's DBO. This way we can do things like inserting stuff into tables without manually entering credentials in our script.
here is the joomla bootstrap code for joomla 3.x. Make sure your JOOMLA_PATH is correct, it should be the path of your Joomla installation