V
V
Vladislav Startsev2016-02-08 10:50:02
PHP
Vladislav Startsev, 2016-02-08 10:50:02

What's wrong with connecting to a database in ZendFramewor 2?

Actually, the whole code, as a result, when I write var_dump($this->news) in the view, I get NULL, i.e. the request returned NULL, the database is configured, the scripts seem to be the same, which I don’t understand.
Code in global.php

return array(
   'db' => array(
    'driver'	=> 'Pdo',
    'dsn'		=> 'mysql:dbname=test_task;host=localhost',
    'driver_options' => array(
      PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES UTF8'
    ),
  ),
  'service_manager' => array(
        'factories' => array(
            'Zend\Db\Adapter\Adapter' => 'Zend\Db\Adapter\AdapterServiceFactory',
        ),
    ),
);

Code in local.php
return array(
   'db' => array(
    'username'	=> 'root',
    'password'	=> '',
  ),
);

Controller code
public function indexAction()
    {
    $adapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
    $news = new NewsTable($adapter);
    return array(
     'news' => $news->fetchAll(),
    );
    }

Model Code
...
use Zend\Db\Sql\Sql;
class NewsTable
{
  private $sql;
  public function __construct($adapter)
  {
    $this->sql = $adapter;
  }
  public function fetchAll()
    {
  $resultSet = $this->sql->query('SELECT * FROM news ORDER BY news_id');
    foreach($resultSet as $k=>$v){
      $res[$k]=$v;
    }
        return $res;
    }
...
}

ps I have already tried a bunch of ways, only this one and this one are connected, and the second one even works, but I need to work through regular SQL with several tables, and the second option connects to only one.
p.s.s. Maybe someone knows how it is even easier to just connect to the database and work with ->query('QUERY'), only without doctrine or orms.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Khodyrev, 2016-02-08
@esvlad

$st = $this->sql->query('SELECT * FROM news ORDER BY news_id');
$resultSet = $st->execute();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question