在Zend Framework中搜索一组记录

时间:2013-03-28 09:12:45

标签: php mysql zend-framework

我已编写代码来搜索名字和姓氏并显示那些特定记录(如果可用)并对这些记录执行更新和删除等操作,我已编写以下代码进行搜索,请告诉我什么是正确的构建搜索控制器的方法。我收到以下错误:

Message: Method "select" does not exist and was not trapped in __call()

我在控制器中编写的代码是:

public function searchAction($params)
{
    $query = $this->select()
                 ->from(
                array('EMPLOYEES'),
                array('FIRST_NAME','LAST_NAME','SALARY','HIREDATE')
                );
$query = $this->_makeParams($query,$params);
return $this->fetchAll($query);
}

private function _makeParams($query, $params)
{
    $firstname = isset($params['firstname']) ? trim($params['firstname']) : '';
    $lastname = isset($params['lastname']) ? trim($params['lastname']) : '';
$salary = isset($params['salary']) ? trim($params['salary']) : '';
$hiredate= isset($params['hiredate']) ? trim($params['hiredate']) : '';

if($firstname!='')
{
    $name = '%'.$this->quote($firstname).'%';//quote is my own function
    $query->where("EMPLOYEES.FIRST_NAME LIKE '?'",$firstname); 
    }

if($lastname!='')
{
    $query->where("EMPLOYEES.LAST_NAME =?",$lastname);
}

if($salary!='')
{
    $query->where("EMPLOYEES.SALARY=?",$salary);
}

if($hiredate!='')
{
    $query->where("EMPLOYEES.HIRE_DATE=?",$hiredate);
}
 }

2 个答案:

答案 0 :(得分:1)

public function searchAction($params)
{
    $db      = Zend_Registry :: get('db');
    $select  = $db->select();
    $query = $select->from(
                array('EMPLOYEES'),
                array('FIRST_NAME','LAST_NAME','SALARY','HIREDATE')
                );
$query = $this->_makeParams($query,$params);
return $this->fetchAll($query);
}

您收到错误是因为您尚未创建Zend注册表的对象。所以复制该函数并替换您的代码

答案 1 :(得分:1)

您的错误来自于您对控制器对象而不是数据库对象调用select()的事实:

public function searchAction($params)
{
    //$this in this context is a Zend_Controller_Action object
    //you need to query against your database object.
    $db = Zend_Db_Table::getDefaultAdapter();
    $query = $db->select()
                 ->from(
                array('EMPLOYEES'),
                array('FIRST_NAME','LAST_NAME','SALARY','HIREDATE')
                );
$query = $this->_makeParams($query,$params);
//again make sure to query against the database object
return $db->fetchAll($query);
}

如果您没有在bootstrap.php或application.ini中创建数据库对象,则可以使用Zend_Db创建一个:

$db = Zend_Db::factory('Pdo_Mysql', array(
    'host'     => '127.0.0.1',
    'username' => 'webuser',
    'password' => 'xxxxxxxx',
    'dbname'   => 'test'
));