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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With