Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Joomla 3.1: accessing database from an external PHP

I have an external PHP script and I'm doing the query using PDO as such:

try
{
    $dbh = new PDO("mysql:host=$hostname;dbname=$db", $username, $password);
    $sql = "SELECT * FROM $table WHERE userName=:userName";
    $stmt = $dbh->prepare($sql);
    $stmt->bindParam(':userName', $userName);
    $stmt->execute();
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
    $dbh = null;
}
catch(PDOException $e)
{
    echo $e->getMessage();
}

As I am new to Joomla/PHP, I am not sure if this is a good practice. Is there any security risk with my current set up? I just found out that it is possible to use JFactory in an external script, but I just want to know if changing to JFactory is a must in my case, or I could just stick to using PDO?

like image 401
cottoncandy89 Avatar asked Mar 04 '14 04:03

cottoncandy89


1 Answers

Try this ,

define( '_JEXEC', 1 );
define('JPATH_BASE', dirname(__FILE__) );//this is when we are in the root,means path to Joomla installation
define( 'DS', DIRECTORY_SEPARATOR );

require_once ( JPATH_BASE .DS.'includes'.DS.'defines.php' );
require_once ( JPATH_BASE .DS.'includes'.DS.'framework.php' );

$app = JFactory::getApplication('site');
$app->initialise();
$db = JFactory::getDBO();// Joomla database object

For more about Joomla database usage ,select operation.

This is much better compared to explicitly providing DB name and host name.

Hope its make sense..

like image 80
Jobin Avatar answered Oct 18 '22 12:10

Jobin