简体   繁体   中英

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?

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..

Its odd. Someone asks a question and people reply with irrelevant answers. The question here is how to access joomla database using php pdo but the irrelevant answers were use Joomla's internal code.

Sigh!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM