【问题标题】:How do i execute queries and fetch data from the result in ZEND 2?如何在 ZEND 2 中执行查询并从结果中获取数据?
【发布时间】:2014-12-29 15:42:48
【问题描述】:

我想以老式方式在 zend2 中执行查询。我想编写查询并执行它。我不想使用函数 save()、update()、delete()。 这是我的模型:

    namespace Application\Model;

   use Zend\Db\Adapter\Adapter;
use Zend\Db\TableGateway\AbstractTableGateway;
use Zend\Db\Sql\Select;
use Zend\Db\Sql\Sql;
use Zend\Db\Adapter\Driver\ResultInterface;
use Zend\Db\ResultSet\ResultSet;

    class UsersTable extends AbstractTableGateway {


        public function __construct(Adapter $adapter) {
            $this->adapter = $adapter;
        }

        public function fetchAll() {

            $results  = $this->adapter->query("SELECT * FROM users");
            return $results->execute();
        }

    }

在 fetchAll 函数中,我想执行查询“select * from users”。我怎样才能做到这一点 ? 结果是:

    object(Zend\Db\Adapter\Driver\Pdo\Result)#243 (8) {
  ["statementMode":protected]=>
  string(7) "forward"
  ["resource":protected]=>
  object(PDOStatement)#241 (1) {
    ["queryString"]=>
    string(19) "SELECT * FROM users"
  }
  ["options":protected]=>
  NULL
  ["currentComplete":protected]=>
  bool(false)
  ["currentData":protected]=>
  NULL
  ["position":protected]=>
  int(-1)
  ["generatedValue":protected]=>
  string(1) "0"
  ["rowCount":protected]=>
  NULL
}

【问题讨论】:

  • 我猜这是一个很难的问题:))

标签: zend-framework2


【解决方案1】:

您可以执行以下操作,而不是循环结果集并调用 next():

public function fetchAll() {
    $results  = $this->adapter->query("SELECT * FROM users");
    $result = $results->execute();
    return $result->getResource()->fetchAll();
}

函数会将数据作为数组返回。

【讨论】:

  • fetchAll() 是一个 PDO 函数。在另一种情况下它可能不存在!?
【解决方案2】:

你会做一个数组

public function fetchAll() {
    $stmt = $this->adapter->query('SELECT * FROM user');
    $result = $stmt->execute();
    if($result->count() > 0) {
        $returnArr = array();
        while ($result->valid()) {
            $returnArr[] = $result->current();
            $result->next();
        }
        if(count($returnArr) > 0) {
            return $returnArr;
        }
    }
    return FALSE;
}

【讨论】:

  • 当前函数是做什么的?我只是不明白为什么我需要它? thxx
  • 你想要什么?此函数将表用户的内容作为数组提供给您。
  • “您可以通过执行以下操作来避免 foreach 循环”:在此处查看最后一个答案:stackoverflow.com/questions/14107346/…。使用这个答案,您正在制作一个额外的循环,因此这不是最佳做法。
【解决方案3】:
$result = fetchAll();
foreach($result as $row){
    $row->column1
    $row->column2
}

$result = $result->toArray();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-25
    • 2017-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多