Use Existing Joomla Configuration in External PHP file | 2008-06-25

Technology Blog » Web Development

Sometimes you may need to write an external Php file in stead of working in Joomla files. Outside the Joomla Framework, we can not use Joomla DB libraries, such as Global object $db, loadResult(), loadResultArray, loadAssocList, loadRow() and etc.

In this case, we can use the custom PHP code plugin to write the code right in the Joomla content page.

Or you can try what I do here: Include Joomla configuration and write your own MySQL queries in external php file......

 

Joomla Configuration

If you open configuration.php, you will see that all variables inside are under the class JConfig().
In my example here, I need the variables of $host, $db, $user and $password

 

Joomla page

Suppose we have a Joomla page called "jm_page.php"

in jm_page.php, I tired to POST a request variable of $user_id from "jm_page.php" to external php file called "external.php".

<form action="external.php" method="POST">
<input type="text" name="user_id" id="user_id" value="<?php echo $user_id; ?>" />
<input type="submit" />
</form>

 

External Page

In the code I wrote below, the objective is to use Jconfig Class without re-giving Database connection strings which were already defined in Joomla Configuration page.

Having the DB established, we query and output the first value in the $result Array.

In the Query, I tried to get the result of sex of the user base on the user id from the table "jos_community_user".

How to read $jconfig->host?
$Jconfig is now the instance of the Jconfig class. host is the variable $host inside the class.

<?php
#### The following codes is written by Andy Ng <http://www.pcinvent.com> ####
#### Please keep the above credit line to the Autor ####

//get POST
$user_id = $_POST["user_id"];
echo $user_id;

//use joomla db class
require("configuration.php");
$jconfig = new JConfig();

//db establish
$db_error = "I am sorry! We are maintenaning the website, please try again later.";
$db_config = mysql_connect( $jconfig->host, $jconfig->user, $jconfig->password ) or die( $db_error );
mysql_select_db( $jconfig->db, $db_config ) or die( $db_error );

//db query result
$query = "SELECT user_sex FROM jos_community_user WHERE user_id = $user_id";//get user_sex
$query_execute = mysql_query($query);
$result = mysql_fetch_row($query_execute);
echo $result[0];

mysql_close($db_config);//andy:close db for security reason
?>