0

当我执行下面的函数时,查询执行成功,但我在查询结果上方收到警告:

mysql_num_rows() 期望参数 1 是资源,布尔值

我该如何解决?

public function retrieve()
{
    $id=JRequest::getVar('id');
    $db =JFactory::getDBO();
    $sql="select * 
          from 
            #__npco_car,#__npco_namayeshgah,#__npco_agahi
          where 
            #__npco_car.car_id='$id' and
            #__npco_namayeshgah.id_namayeshgah=#__npco_agahi.id_namayeshgah and 
            #__npco_car.car_id=#__npco_agahi.car_id
     ";
    $db->setQuery($sql);

    $db->query();
    $row = $db->getNumRows();

    if($row == 1) {
        return $db->loadAssocList();   
    } else {
        $db = JFactory::getDBO();
        $sql="select * 
              from 
                 #__npco_car,#__npco_useragahi,#__npco_user
              where 
                 #__npco_car.car_id='$id' and 
                 #__npco_user.id_user=#__npco_useragahi.id_user and 
                 #__npco_car.car_id=#__npco_useragahi.car_id
        ";
        $db->setQuery($sql);
        return $db->loadAssocList();
    }
}
4

2 回答 2

1

您的代码有几个问题。

  1. 切勿使用未经检查/未经验证的请求值,即使在示例中也不行!
  2. 使用查询生成器。
  3. 通过 a) 在构造函数中设置数据库来减少耦合,这已经在模型中完成,b) 在控制器中检索 id。
  4. 您尝试从多个表中获取所有字段 (*),这些表有一些共同的列名。那不管用。
  5. 看看 JOIN。

这将起作用:

public function retrieve($id)
{
    $query = $this->_db->getQuery(true);
    $query->select('#__npco_car.*')->from(array('#__npco_car', '#__npco_namayeshgah', '#__npco_agahi'));
    $query->where('#__npco_car.car_id = ' . (int) $id);
    $query->where('#__npco_namayeshgah.id_namayeshgah = #__npco_agahi.id_namayeshgah');
    $query->where('#__npco_car.car_id = #__npco_agahi.car_id');

    $this->_db->setQuery($sql);
    $rows = $this->_db->loadAssocList();

    if (empty($rows))
    {    
        $query = $this->_db->getQuery(true);
        $query->select('#__npco_car.*')->from(array('#__npco_car, #__npco_useragahi, #__npco_user'));
        $query->where('#__npco_car.car_id = ' . (int) $id);
        $query->where('#__npco_user.id_user = #__npco_useragahi.id_user');
        $query->where('#__npco_car.car_id = #__npco_useragahi.car_id');
        $db->setQuery($sql);
        $this->_db->setQuery($sql);
        $rows = $this->_db->loadAssocList();
    }

    return $rows;
}
于 2013-08-08T13:00:38.603 回答
0

可能这是你的问题..

更改您的查询如下

 $sql="select * 
          from 
            #__npco_car,#__npco_namayeshgah,#__npco_agahi
          where 
            #__npco_car.car_id='".$id."' and
            #__npco_namayeshgah.id_namayeshgah=#__npco_agahi.id_namayeshgah and 
            #__npco_car.car_id=#__npco_agahi.car_id
     ";


 $sql="select * 
              from 
                 #__npco_car,#__npco_useragahi,#__npco_user
              where 
                 #__npco_car.car_id='".$id."' and 
                 #__npco_user.id_user=#__npco_useragahi.id_user and 
                 #__npco_car.car_id=#__npco_useragahi.car_id
        ";
于 2013-08-08T05:35:27.873 回答