使用Joomla语法查询MySQL

时间:2013-11-10 23:00:29

标签: php mysql joomla

以下查询返回我期望的结果:

$link=mysqli_connect('localhost','user','pass');
    if(!$link){
    echo "No connection!";
    exit();
    }

    if (!mysqli_set_charset($link, 'utf8'))
    {
      echo 'Unable to set database connection encoding.';
      exit();
    }

    if(!mysqli_select_db($link, 'database')){
        echo "No database";
    exit();
};

$res = $link->query("SELECT rules FROM xmb9d_viewlevels WHERE id=10");

while ($row = $res->fetch_array()) {
    echo " cenas = " . $row['rules'] . "\n";
};

但是,因为我正在使用Joomla 2.5.16并且我试图保持其语法,所以我尝试了:

$db = JFactory::getDbo();
$query = $db->getQuery(true); 

$res = $db->query("SELECT rules FROM #__viewlevels WHERE id=10");

while ($row = $res->fetch_assoc()) {
    echo " cenas = " . $row['rules'] . "\n";
};

这不起作用。它只显示文本“cenas =”。

此代码有什么问题?

1 个答案:

答案 0 :(得分:1)

尝试以下方法:

$db = JFactory::getDbo();

$query = $db->getQuery(true);

$query->select($db->quoteName('rules'))
 ->from($db->quoteName('#__viewlevels'))
 ->where($db->quoteName('id')." = ".$db->quote('10'));

$db->setQuery($query);

$results = $db->loadObjectList();

foreach ( $results as $result) {
   echo " cenas = " . $result->rules;
}