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

1$db = Zend_Db::factory('Pdo_Mysql', array(
2    'host'     => '127.0.0.1',
3    'username' => 'myUser',
4    'password' => 'myPassword',
5    'dbname'   => 'myDatabase'
6));

SELECT statement
eg.

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

is written in Zend_Db syntax like this:

1$db->select()
2  ->from('students', array('fname', 'course', 'grade'))
3  ->where('student_id = ?', $student_id)
4  ->order('grade DESC');

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

INSERT statement
eg.

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

Zend_Db syntax:

1$student = array( 'id' => new Zend_Db_Expr('id + 1'),
2                  'email' => $email,
3                  'passwrd' => $passwrd,
4                  'fname' => $fname,
5                  'address' => $address,
6                  'active' => '1');
7 
8$db->insert('students', $student);

UPDATE statement
eq.

1UPDATE students
2   SET passwrd = '{$passwrd}',
3       fname = '{$fname}',
4       address = '{$address}',
5       active = 1
6WHERE id = '{$student_id}'

Zend_Db syntax:

1$student = array('passwrd' => $passwrd,
2                 'fname' => $fname,
3                 'address' => $address,
4                 'active' => '1');
5 
6$db->update('students', $student, 'id = ' . $student_id);

DELETE statement
eq.

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

Zend_Db syntax:

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

Tested in Zend Framework 1.10.8 on OSX 10.7.4

Comments are closed.