php Notices of Undefined Variable&试图获得非对象的属性

时间:2013-08-24 12:25:17

标签: php joomla joomla2.5

学习与学习通过处理Joomla项目来执行php 如何改进此代码&解决PHP通知 - 任何建议 - 解决方案 - 非常感谢!!

注意:未定义的变量:第140行的* / home / mygames / public_html / components / com_toys / models / category.php中的cond (这是$ sql行)*

   function loadSubCat($id,$Carmodel,$minprice,$maxprice){
   $mainframe =& JFactory::getApplication();
   $option = JRequest::getCmd('option');
   $database =& JFactory::getDBO();
   global $Itemid;  
   if($Carmodel!="")
   $cond=" and prod_id='$Carmodel' ";
   $sql = "Select * from #__toycar_products Where prod_cat_id='".$id."' $cond and prod_status='1' and prod_id in (select v_prod_id from #__toycar_variants)  Order By prod_sorder";

注意:尝试在第200行的/home/truecar7/public_html/components/com_toys/models/category.php中获取非对象的属性

第200行返回$ row-> id;

   function getItemIdByName($Name){
   $mainframe =& JFactory::getApplication();
   $option = JRequest::getCmd('option');
   $database =& JFactory::getDBO();
   $sql = "Select id  from #__menu Where name = '".$Name."'";
   $database->setQuery($sql);
   $row = $database->loadObject();
   return $row->id;
}

修改

Hello Lodder& Elin,它可以工作但是这样,否则它会在返回$ row行显示未定义的变量通知。

function getItemIdByName($Name){
$db = JFactory::getDBO();
$query = $db->getQuery(true);
$query->select('*')
 ->from('#__menu')      
 ->where('id = ' . $db->quote($Name));      
$db->setQuery($query);
$rows = $db->loadObjectList();

foreach ($rows as $row){
    $row = $row->msg;
     }    
$row='';
return $row;
}

2 个答案:

答案 0 :(得分:2)

对于Undefined Notice,您必须像这样修改代码

$cond = '';
if($Carmodel!="") {
   $cond = " and prod_id='$Carmodel' ";
}

对于Trying to get property of non-object注意:我认为$row为空,这就是抛出通知的原因。检查$row

var_dump($row);

问题:

$database->loadObject(); // This line

答案 1 :(得分:2)

尝试使用以下内容。我对您的函数进行了一些更改,并使用Joomla 2.5编码标准进行数据库查询。

$Name = "XXXXXXXXX";  //define the name variable

function getItemIdByName($Name){
    $db = JFactory::getDBO();
    $query = $db->getQuery(true);
    $query->select('*')
     ->from('#__menu')      
     ->where('id = ' . $db->quote($Name));      
    $db->setQuery($query);
    $rows = $db->loadObjectList();

    foreach ($rows as $row){
        $row = $row->msg;
    }
    return $row;
}

echo getItemIdByName($Name); //echo the result of the function