Joomla 3.1:从外部PHP访问数据库

时间:2014-03-04 04:22:35

标签: php mysql joomla pdo

我有一个外部PHP脚本,我正在使用PDO进行查询:

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();
}

由于我是Joomla / PHP的新手,我不确定这是不是一个好习惯。 我目前设置的安全风险是否存在? 我刚刚发现可以在外部脚本中使用JFactory,但我只是 想知道在我的情况下是否必须更改为JFactory,或者我可以坚持使用PDO?

1 个答案:

答案 0 :(得分:5)

试试这个,

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

有关Joomla database用法的更多信息,请select operation

与明确提供数据库名称和主机名相比,这要好得多。

希望它有意义..