Reputation: 1
I have a problem in writing sql query in zend framework model.
I want to write native sql query in zend framework models.
Thanks in advance.
Upvotes: 0
Views: 4837
Reputation: 642
To expand Bryan's answer :)
First, you have to create a "database adapter" what connects to your database. Each supported database engine has a specific adapter class. The database engine could be MySQL, PostgreSQL..etc you can find all here: http://framework.zend.com/manual/en/zend.db.adapter.html
For example you can create a MySQL specific adapter like this:
$dbAdapter = new Zend_Db_Adapter_Pdo_Mysql(array(
'host' => 'localhost',
'username' => 'webuser',
'password' => 'xxx',
'dbname' => 'test'
));
Then if you have a native SQL query, like:
$sql = "SELECT * FROM users WHERE id > 23";
then you can use the above $dbAdapter
object to run this native query, using its query()
function:
$statement = $dbAdapter->query($sql);
Now the $statement variable will be a Zend_Db_Statement object. If you want to see the result of this query you can use the fetch()
function, like:
while ($row = $statement->fetch()) {
echo $row['username'];
}
While its easy to use, its not the best technique to use the above query() method because
it not helps to promote database-independent queries.
To write database independent queries you can use Zend_Db_Select
. But of course, sometimes its not avoidable to use native queries. You can find here an example how can you write these queries for more db engines:
Zend_Db_Select order by random, compatible in mssql / mysql
Based on this example you can use different queries based on your adapter's type..
Upvotes: 3