Zend_Db syntax cheat sheet

A small cheat sheet with simple examples for the Zend_Db syntax in Zend Framework. A smooth way to write sql that will work on many different databases

Connect to database

$db = Zend_Db::factory('Pdo_Mysql', array(
    'host'     => '',
    'username' => 'myUser',
    'password' => 'myPassword',
    'dbname'   => 'myDatabase'

SELECT statement

SELECT fname, course, grade FROM students 
   WHERE student_id = {$student_id} ORDER BY grade DESC

is written in Zend_Db syntax like this:

  ->from('students', array('fname', 'course', 'grade'))
  ->where('student_id = ?', $student_id)
  ->order('grade DESC');

If you want to fetch all columns (*), just remove the array(‘name’,…) in the from function

INSERT statement

INSERT INTO students(id, email, passwrd, fname, address, active) 
   VALUES (id + 1, '{$email}', '{$passwrd}', '{$fname}', '{$address}', 1);

Zend_Db syntax:

$student = array( 'id' => new Zend_Db_Expr('id + 1'),
                  'email' => $email,
		          'passwrd' => $passwrd,
		          'fname' => $fname,
		          'address' => $address,
		          'active' => '1');

$db->insert('students', $student);

UPDATE statement

UPDATE students
   SET passwrd = '{$passwrd}',
       fname = '{$fname}',
       address = '{$address}',
       active = 1
WHERE id = '{$student_id}'

Zend_Db syntax:

$student = array('passwrd' => $passwrd,
                 'fname' => $fname,
                 'address' => $address,
                 'active' => '1');

$db->update('students', $student, 'id = ' . $student_id);

DELETE statement

DELETE FROM students WHERE id = '{$student_id}'

Zend_Db syntax:

$db->delete('students', 'id = ' . $student_id);

Tested in Zend Framework 1.10.8 on OSX 10.7.4

Leave a Comment

NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre lang="" line="" escaped="" cssfile="">

This site uses Akismet to reduce spam. Learn how your comment data is processed.