How to run raw SQL Query with Zend Framework 2

后端 未结 4 1611
离开以前
离开以前 2020-12-30 04:14

Is there a way to execute a SQL String as a query in Zend Framework 2?

I have a string like that:

$sql = \"SELECT * FROM testTable WHERE myColumn = 5         


        
4条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-12-30 04:51

    Just pass the sql string to your db adapter like this:

    $resultSet = $adapter->query($sql, \Zend\Db\Adapter\Adapter::QUERY_MODE_EXECUTE);
    

    And if you want to pass parameters:

    $sql = "SELECT * FROM testTable WHERE myColumn = ?";
    $resultSet = $adapter->query($sql, array(5));
    

    EDIT: Please note that the query method does not always returns a resultset. When its a resultset producing query(SELECT) it returns a \Zend\Db\ResultSet\ResultSet otherwise(INSERT, UPDATE, DELETE, ...) it will return a \Zend\Db\Adapter\Driver\ResultInterface.

    And when you leave the second Parameter empty you will get a \Zend\Db\Adapter\Driver\StatementInterface which you can execute.

提交回复
热议问题