Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run raw SQL Query with Zend Framework 2

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"

now I want to execute this string directly.

like image 926
nopaws Avatar asked Mar 11 '13 06:03

nopaws


People also ask

What is raw SQL query?

Raw SQL, sometimes also called native SQL, is the most basic, most low-level form of database interaction. You tell the database what to do in the language of the database. Most developers should know basics of SQL. This means how to CREATE tables and views, how to SELECT and JOIN data, how to UPDATE and DELETE data.

How do I run a raw query in CI?

Syntax for Raw Query MethodUse query() method of CodeIgniter 4. $db = db_connect(); OR $db = \Config\Database::connect(); It will connect with default connection group of application. Now, by using $db we can write and run queries.


1 Answers

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.

like image 113
Weteef Avatar answered Sep 24 '22 11:09

Weteef