Zend Framework database operation skills summary, zendframework
This example summarizes the Zend Framework database operations. We will share this with you for your reference. The details are as follows:
Zend_Db database knowledge
Example:
Model file:
$ This-> fetchAll ("is_jian = 1", "id DESC",)-> toArray (); // according to is_jian = 1, sort by id in reverse order. When the first two records are null, the ASC is directly sorted by id in reverse order.
Route file:
$ Video = new Video (); // instantiate the database class $ this-> view-> get2Video = $ video-> get2Video (); // obtain the data recommended on the home page
Index. phtml file:
<?php foreach ($this->get2Video as $video): ?><?=$video['id']; ?><?=$video['name']; ?><? endforeach; ?>
Add quotation marks to prevent database attacks
Quote usage
$ Value = $ db-> quote ('st John "s wort '); // $ value is now '"St John \" s Wort "' (note the quotation marks on both sides) // enclose the array with quotation marks $ value = $ db-> quote (array ('A', 'B', 'C ')); // $ value is now '"a", "B", "c"' ("," separator string)
QuoteInto usage
Echo $ where = $ db-> quoteInto ('Id =? ', 1); // $ where is now 'id = "1"' (note the quotation marks on both sides) // IN the where statement, enclose the array with quotation marks $ where = $ db-> quoteInto ('Id IN (?) ', Array (1, 2, 3); // $ where is now 'Id IN ("1", "2", "3 ") '(a comma-separated string)
(1) Data Query Summary
Directly query (using the complete SQL statement)
// Function quoteInto ($ text, $ value, $ type = null, $ count = null) $ db = $ this-> getAdapter (); $ SQL = $ db-> quoteInto ('select * FROM'm _ video' WHERE 'is _ guo' =? ', '1'); $ result = $ db-> query ($ SQL ); // use the PDOStatement object $ result to put all the result data into an array $ videoArray = $ result-> fetchAll ();
FetchAll usage
fetchAll($where = null, $order = null, $count = null, $offset = null)
Return the values of all fields in the result set as a continuous array. If the parameter is not set, it is written as null.
Number of results that can be retrieved
$videoArray=$this->fetchAll("is_jian=1 and is_guo=1","id DESC",0,2)->toArray();
FetchAssoc usage
fetchAssoc($sql, $bind = array())
Retrieve the values of all fields in the result set and return them as the associated array. The first field is used as the code.
$db = $this->getAdapter();$videoArray=$db->fetchAssoc("SELECT * FROM m_video WHERE `is_jian` = :title",array('title' => '1'));
FetchCol usage
fetchCol($sql, $bind = array())
Retrieve the first field name of all result rows
$db = $this->getAdapter();$videoArray=$db->fetchCol("SELECT name FROM m_video WHERE `is_jian` = :title",array('title' => '1'));
FetchOne usage
fetchOne($sql, $bind = array())
Retrieve only the first field value
$db = $this->getAdapter();echo $videoArray=$db->fetchOne("SELECT count(*) FROM m_video WHERE `is_jian` = :title",array('title' => '1'));
FetchPairs usage
fetchPairs($sql, $bind = array())
Retrieves an array. The first field value is a code (id), and the second field is a value (name)
Return Value: Array ([1] => Chinese zodiac [2] => peach blossom luck), 1, 2: id field.
$db = $this->getAdapter();$videoArray=$db->fetchPairs("SELECT id, name FROM m_video WHERE is_jian = :title",array('title' => '1'));
FetchRow usage
fetchRow($where = null, $order = null)
Retrieve only the first row of the result set
$videoArray=$this->fetchRow("is_jian=1 and is_guo=1", 'id DESC')->toArray();
Query usage
// Function query ($ SQL, $ bind = array () $ db = $ this-> getAdapter (); $ result = $ db-> query ('select * FROM'm _ video ''); // $ result = $ db-> query ('select * FROM'm _ video' WHERE 'name' =? AND id =? ', Array ('zodiac romance', '1'); // $ result-> setFetchMode (Zend_Db: FETCH_OBJ); // FETCH_OBJ is the default value, FETCH_NUM, FETCH_BOTH // while ($ row = $ result-> fetch () {// echo $ row ['name']; ///} // $ rows = $ result-> fetch (); // $ rows = $ result-> fetchAll (); // $ obj = $ result-> fetchObject (); // echo $ obj-> name; // echo $ Column = $ result-> fetchColumn (0 ); // obtain the first field of the result set. For example, if 0 is the ID number, print_r ($ rows) is used to retrieve only one field );
Select usage
$ Db = $ this-> getAdapter (); $ select = $ db-> select (); $ select-> from ('m _ video', array ('id ', 'name', 'clicks')-> where ('is _ guo =: is_guo and name =: name')-> order ('name ') // sort columns by which columns are added as arrays (multiple fields) or strings (one Field)-> group () // group-> having () // The condition for querying data by group-> distinct () // No parameter is set to remove duplicate values. Sometimes it is the same as the result returned by groupby-> limit (10); // use the bound parameter $ params = array ('is _ guo' => '1 ', 'name' => 'zodiac romance '); // $ SQL = $ select->__ toString (); // obtain the query statement, debug $ result = $ db-> fetchAll ($ select, $ params); execute select query $ stmt = $ db-> query ($ select ); $ result = $ stmt-> fetchAll ();
Or use
$stmt = $select->query();$result = $stmt->fetchAll();
If you use
$db->fetchAll($select)
Same results
Multi-table join query usage
$ Db = $ this-> getAdapter (); $ select = $ db-> select (); $ select-> from ('m _ video', array ('id ', 'name', 'pic ', 'actor', 'Type _ id', 'Up _ Time')-> where ('is _ guo =: is_guo and is_jian =: is_jian ')-> order ('up _ Time')-> limit (2); $ params = array ('is _ guo' => '1 ', 'Is _ jian '=> '1'); $ select-> join ('m _ type','m _ video. type_id = m_type.t_id ', 'Type _ name'); // multi-table joint query $ videoArray = $ db-> fetchAll ($ select, $ params );
The find () method. You can use the primary key value to retrieve data in the table.
// SELECT * FROM round_table WHERE id = "1"$row = $table->find(1);// SELECT * FROM round_table WHERE id IN("1", "2", 3")$rowset = $table->find(array(1, 2, 3));
(2) data deletion Summary
Method 1: You can delete any table.
// QuoteInto ($ text, $ value, $ type = null, $ count = null) $ table ='m _ video '; // set the table for data deletion $ db = $ this-> getAdapter (); $ where = $ db-> quoteInto ('name =? ', 'Ccc'); // where Condition Statement for data deletion echo $ rows_affected = $ db-> delete ($ table, $ where ); // Delete the data and obtain the number of affected rows
Method 2: only
// Delete usage // delete ($ where) $ where = "name = 'bbb'"; echo $ this-> delete ($ where ); // Delete the data and obtain the number of affected rows
(3) Data Update Summary
Method 1: Any table can be updated.
// Construct an update array in the format of "column name" => "data" and update the data row $ table ='m _ video '; // update the data table $ db = $ this-> getAdapter (); $ set = array ('name' => 'butterfly shadow ', 'clicks' => '20140901',); $ where = $ db-> quoteInto ('Id =? ', '10'); // where statement // update table data, returns the number of updated rows echo $ rows_affected = $ db-> update ($ table, $ set, $ where );
Method 2: only
$ Set = array ('name' => ' 22', 'clicks' => '000000',); $ db = $ this-> getAdapter (); $ where = $ db-> quoteInto ('Id =? ', '10'); // where statement $ rows_affected = $ this-> update ($ set, $ where); // update table data and return the number of updated rows
(4) data insertion Summary
Method 1: you can insert data into any table.
$ Table ='m _ gao'; // data table inserted $ db = $ this-> getAdapter (); // construct an insert array in the format of "column name" => "data" and insert a data row $ row = array ('title' => 'Hello, everyone. 111 ', 'content' =>' video and TV network should be developed with zend framework ', 'time' => '2017-05-04 17:23:36 ',); // insert data rows and return the number of inserted rows $ rows_affected = $ db-> insert ($ table, $ row ); // The Last inserted data idecho $ last_insert_id = $ db-> lastInsertId (); $ row = array ('name' => 'curdate ()', 'address' => new Zend_Db_Expr ('curdate ()'))
In this way, the field name inserts a string of curdate (), and the address inserts a time value (curdate () result)
Method 2: it can only be applicable to the table that has not been summarized.
(5) Transaction Processing
$ Table ='m _ gao'; // data table inserted $ db = $ this-> getAdapter (); $ db-> beginTransaction (); // The Zend_Db_Adapter will return to the automatic commit mode until you call the beginTransaction () method again. // construct the inserted array in the format of "column name" => "data, insert data row $ row = array ('id' => null, 'title' => 'Hello, everyone. 111 ', 'content' =>' video and TV network should be developed with zend framework ', 'time' => '2017-05-04 17:23:36 ',); try {// insert data rows and return the number of inserted rows $ rows_affected = $ db-> insert ($ table, $ row ); // The Last inserted data id $ last_insert_id = $ db-> lastInsertId (); $ db-> commit (); // transaction commit} catch (Exception $ e) {$ db-> rollBack (); echo 'capture exception :'. $ e-> getMessage (); // exception message} echo $ last_insert_id;
(6) Others
$ Db = $ this-> getAdapter (); $ tables = $ db-> listTables (); // list all tables in the current database $ fields = $ db-> describeTable ('m _ video'); // list the fields of a table