0

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.

1
  • 2
    Whats urs req. and what hav u tried? Commented Mar 9, 2012 at 15:21

1 Answer 1

3

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..

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.