php zend framework2 sql execute query返回标量

php zend framework2 sql execute query返回标量

问题描述:

I have a query that i execute within zend framework 2

protected function getCityByZip($zip){
    $adapter = $this->getServiceLocator()->get('myConn');
    $sql = new Sql($adapter);
    $select = $sql->select();
    $select->from(array("cities" => "cities"))
           ->columns(array('cityName'))
           ->where(array("cityZip" => $zip));
    $statement = $sql->prepareStatementForSqlObject($select);
    $result = $statement->execute();
    return $result;
}

i want to do something like

executeScalar();

and get just a single value, and not a result set like i get here from using execute()

how is this possible?

我有一个在zend framework 2中执行的查询 p>

  protected function getCityByZip($ zip){
 $ adapter = $ this-> getServiceLocator() - > get('myConn'); 
 $ sql = new Sql($ adapter); 
 $ select = $  sql-> select(); 
 $ select-> from(array(“cities”=>“cities”))
  - > columns(array('cityName'))
  - > where  (array(“cityZip”=> $ zip)); 
 $ statement = $ sql-> prepareStatementForSqlObject($ select); 
 $ result = $ statement-> execute(); 
 return $ result;  
} 
  code>  pre> 
 
 

我想做类似 p>

executeScalar(); p> blockquote>

只获得一个值,而不是像我从使用execute()到达此处的结果集 p>

这怎么可能? p> div>

I don't know if this is what you're looking for, but if you want your function getCityByZip($zip) returns a single value you can do this :

protected function getCityByZip($zip){
    $adapter = $this->getServiceLocator()->get('myConn');
    $sql = new Sql($adapter);
    $select = $sql->select();
    $select->from(array("cities" => "cities"))
           ->columns(array('cityName'))
           ->where(array("cityZip" => $zip));
    $statement = $sql->prepareStatementForSqlObject($select);
    $resultSet = $statement->execute();

    $current = $resultSet->current();

    return $current->cityName;
}

EDIT :

I think what you're looking for is the fetchOne() method which was in ZF1 DB Adapter (see this Fetching a Single Scalar from a Result Set) but not in ZF2. In ZF1 you could do this :

$db->fetchOne('SELECT cityName FROM users WHERE cityZip='.$zip);

But the equivalent, in ZF2, takes several lines of code as the above function.

Hope this could help.