0

Hi i am new to ZF2 and not familiar with some of the changes in ZF2. I would like to know how can i execute SQL query directly from Controller.

I have the following code:

 public function indexAction()
 {
    $db = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
    $sql = "SELECT * FROM books";
    $statement = $db->query($sql);
    $res =  $statement->execute();

    if($res instanceof ResultInterface && $res->isQueryResult()){
        $resultSet = new ResultSet;
        $resultSet->initialize($res);

        foreach($resultSet as $row){
            echo $row->title . PHP_EOL;
        }
    }
    exit;

    /*
    return new ViewModel(array(
        'books' => $this->getBooksTable()->fetchAll(),
    ));
    */
 }

When the controller above is opened in web browser, it does not show anything. If i echo "Blahh.." before the if statement, it displays the "Blahh.." text correctly.

Does anyone know why it does not display the query result properly? Thx.

1 Answer 1

1

try to add this in the top of your controller :

use Zend\Db\Adapter\Driver\ResultInterface;
use Zend\Db\ResultSet\ResultSet;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.