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 ( |
3 | 'username' => 'myUser' , |
4 | 'password' => 'myPassword' , |
5 | 'dbname' => 'myDatabase' |
SELECT statement
eg.
1 | SELECT fname, course, grade FROM students |
2 | WHERE student_id = {$student_id} ORDER BY grade DESC |
is written in Zend_Db syntax like this:
2 | ->from( 'students' , array ( 'fname' , 'course' , 'grade' )) |
3 | ->where( 'student_id = ?' , $student_id ) |
If you want to fetch all columns (*), just remove the array(‘name’,…) in the from function
INSERT statement
eg.
1 | INSERT 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' ), |
8 | $db ->insert( 'students' , $student ); |
UPDATE statement
eq.
2 | SET passwrd = '{$passwrd}' , |
4 | address = '{$address}' , |
6 | WHERE id = '{$student_id}' |
Zend_Db syntax:
1 | $student = array ( 'passwrd' => $passwrd , |
6 | $db ->update( 'students' , $student , 'id = ' . $student_id ); |
DELETE statement
eq.
1 | DELETE 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.