我正在为Joomla编写模块,这时我真的需要能够使用Jfactory连接到数据库。通常一个人可以简单地使用$db = JFactory::getDBO();,但是PHP错误告诉我不包含JFactory类。 所以现在我需要知道如何包括这个JFactory类 。我尝试了一些在互联网上发现的建议,但都没有成功。这是代码(独立运行时完美)
$db = JFactory::getDBO();
<?php // server info $server = 'localhost'; $user = 'ss'; $pass = 'oo'; $db = 'ss'; $connection = mysql_connect($server, $user, $pass) or die ("Could not connect to server ... \n" . mysql_error ()); mysql_select_db($db) or die ("Could not connect to database ... \n" . mysql_error ()); if(isSet($_POST['username'])) { $username = $_POST['username']; $username = mysql_real_escape_string($username); $sql_check = mysql_query("SELECT Username FROM users WHERE Username='$username'"); if(mysql_num_rows($sql_check)) { echo '<font color="#cc0000"><STRONG>'.$username.'</STRONG> is already in use.</font>'; } else { echo 'OK'; } } ?>
希望您能解决我的问题。您的帮助将不胜感激。
尝试1
<?php include('../../../../configuration.php'); include('../../../../libraries/joomla/factory.php'); $config =& JFactory::getConfig(); // server info $server2 = $host; $user2 = $user; $pass2 = $password; $db2 = $db; $connection = mysqli_connect($server2, $user2, $pass2) or die ("Could not connect to server ... \n" . mysqli_error ()); mysqli_select_db($db2) or die ("Could not connect to database ... \n" . mysqli_error ()); if(isSet($_POST['username'])) { $username = $_POST['username']; $username = mysql_real_escape_string($username); $sql_check = mysql_query("SELECT username FROM #__users WHERE username='$username'"); if(mysql_num_rows($sql_check)) { echo '<font color="#cc0000"><STRONG>'.$username.'</STRONG> is already in use.</font>'; } else { echo 'OK'; } } ?>
但这也不起作用。
尝试2(成功)
include('../../../../configuration.php'); $jc = new JConfig(); $table = 'users'; $users = $jc->dbprefix . $table; // connect to the database $mysqli = new mysqli($jc->host, $jc->user, $jc->password, $jc->db);
现在一切正常。现在唯一的事情是:安全。我不太确定这是黑客证明。有人可以评论吗?谢谢 :)
我敢肯定您会发现,但也许对其他人有用
要使用joomla数据库类(即使您不建议使用:)),也需要先定义三个常量,例如:
define( '_JEXEC', 1 ); define( 'DS', DIRECTORY_SEPARATOR ); define( 'JPATH_BASE', $_SERVER[ 'DOCUMENT_ROOT' ] );
然后,您需要包括三个文件,例如:
require_once( JPATH_BASE . DS . 'includes' . DS . 'defines.php' ); require_once( JPATH_BASE . DS . 'includes' . DS . 'framework.php' ); require_once( JPATH_BASE . DS . 'libraries' . DS . 'joomla' . DS . 'factory.php' ); $mainframe =& JFactory::getApplication('site');
编辑
您只能包含两个文件,例如:
define( 'JPATH_BASE', $_SERVER[ 'DOCUMENT_ROOT' ] ); // define JPATH_BASE on the external file require_once( JPATH_BASE . DS . 'libraries' . DS . 'import.php' ); // framework require_once( JPATH_BASE . DS . 'configuration.php' ); // config file
最后使用joomla类,例如: