This article summarizes the Zend Framework database operations. Share it for your reference, as follows:
Zend_Db database knowledge
example:
Model file:
$this->fetchAll("is_jian=1","id DESC",0,2)->toArray(); //According to is_jian=1, sort the first 2 records in reverse order by id. When the first parameter is null, the ASC will be arranged in reverse order by id.
Routing file:
$video=new Video();//Instantiate the database class$this->view->get2Video =$video->get2Video();//Get 2 pieces of recommended data on the homepage
document:
<?php foreach ($this->get2Video as $video): ?> <?=$video['id']; ?> <?=$video['name']; ?> <? endforeach; ?>
Add quotes to prevent database attacks
Usage of quote
$value = $db->quote('St John"s Wort'); // $value now becomes '"St John\"s Wort"' (note the quotes on both sides)// Add quotes to the array$value = $db->quote(array('a', 'b', 'c')); // $value now becomes '"a", "b", "c"' ("," separated string)
quoteInto usage
echo $where = $db->quoteInto('id = ?', 1); // $where is now 'id = "1"' (note the quotes on both sides)// Add quotes to the array in the where statement$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
Direct query. (Use 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 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)
Retrieve the values of all fields in the result set and return them as a continuous array. If the parameter is not set, it will be written as null.
The specified number of pieces of the result set 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 as an associative array, and 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'));
Usage of fetchCol
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'));
Usage of fetchOne
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'));
Usage of fetchPairs
fetchPairs($sql, $bind = array())
Retrieve a related array, the first field value is code (id), and the second field is value (name)
Return: Array( [1] => The 12 Zodiac Signs of Strange Love [2] => Peach Blossom Luck), 1,2: is the id field.
$db = $this->getAdapter(); $videoArray=$db->fetchPairs("SELECT id, name FROM m_video WHERE is_jian = :title",array('title' => '1'));
Usage of fetchRow
fetchRow($where = null, $order = null)
Only the first line of the result set is retrieved
$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('The zodiac signs are strange,', '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);//Get the first field of the result set, such as 0 is the id number, which is used to take only one fieldprint_r($rows);
Usage of select
$db = $this->getAdapter(); $select = $db->select(); $select->from('m_video', array('id','name','clicks')) ->where('is_guo = :is_guo and name = :name') ->order('name')// By what sort of columns, participate as an array (multiple fields) or a string (one field)->group()//Group->having()//Conditions for grouping query data->distinct()// No parameters, remove duplicate values. Sometimes the same result as groupby returns->limit(10); // Use bound parameters to read the result$params = array('is_guo' => '1','name'=>'The 12 Zodiac Signs'); //$sql = $select->__toString();//Get the query statement for debugging$result = $db->fetchAll($select,$params); implementselectQuery $stmt = $db->query($select); $result = $stmt->fetchAll();
Or use
$stmt = $select->query(); $result = $stmt->fetchAll();
If you use it directly
$db->fetchAll($select)
The result is the same
Multi-table joint 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 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) Summary of data deletion
The first method: You can delete any table
//quoteInto($text, $value, $type = null, $count = null) $table = 'm_video';// Set the table to delete data$db = $this->getAdapter(); $where = $db->quoteInto('name = ?', 'ccc');// Where conditional statement for deleting dataecho $rows_affected = $db->delete($table, $where);// Delete the data and get the number of rows affected
The second method: Only delete the
//Delete usage// delete($where) $where = "name = 'bbb'"; echo $this->delete($where);// Delete the data and get the number of rows affected
(3) Data update summary
The first method: you can update any table
// Construct the update array in the format of "column name" => "data" and update the data rows$table = 'm_video';// Updated data table$db = $this->getAdapter(); $set = array ( 'name' => 'Butterfly shadows', 'clicks' => '888', ); $where = $db->quoteInto('id = ?', '10');// where statement// Update table data and return the updated number of rowsecho $rows_affected = $db->update($table, $set, $where);
The second method: Only update the
$set = array ( 'name' => 'Butterfly shadows are heavy 22', 'clicks' => '8880', ); $db = $this->getAdapter(); $where = $db->quoteInto('id = ?', '10');// where statement$rows_affected = $this->update($set, $where);// Update table data and return the updated number of rows
(4) Data insertion summary
The first method: you can insert data in any table
$table = 'm_gao';// Insert data table$db = $this->getAdapter(); // Construct the insert array in the format of "column name" => "data" and insert the data rows$row = array ( 'title' => 'Hello everyone. 111', 'content' => 'The film and television network needs to be developed using zend framework', 'time' => '2009-05-04 17:23:36', ); // Insert data rows and return the number of inserted rows$rows_affected = $db->insert($table, $row); // The last data idecho $last_insert_id = $db->lastInsertId(); $row=array( 'name'=>'curdate()', 'address' => new Zend_Db_Expr ('curdate()') )
In this way, the subfield name will insert a curdate() string, and the address will insert a time value (the result of curdate() 2009-05-09)
The second method: only suitable for the ones in this table have not been summarized yet
(5) Transaction processing
$table = 'm_gao';// Insert data table$db = $this->getAdapter(); $db->beginTransaction();//Zend_Db_Adapter will return to automatic commit mode until you call the beginTransaction() method again// Construct the insert array in the format of "column name" => "data" and insert the data rows$row = array ( 'id'=>null, 'title' => 'Hello everyone. 111', 'content' => 'The film and television network needs to be developed using zend framework', 'time' => '2009-05-04 17:23:36', ); try { // Insert data rows and return the number of inserted rows$rows_affected = $db->insert($table, $row); // The last data id$last_insert_id = $db->lastInsertId(); $db->commit();// Transaction submission}catch (Exception $e){ $db->rollBack(); echo 'Catch exception:'.$e->getMessage();//Exception message is displayed} 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
For more information about Zend, please visit the special topic of this site:Zend FrameWork Framework Introduction Tutorial》、《Summary of excellent development framework for php》、《Yii framework introduction and common techniques summary》、《ThinkPHP Introduction Tutorial》、《PHP object-oriented programming tutorial》、《PHP+mysql database operation tutorial"and"Summary of common database operation techniques for php》
I hope that this article will be helpful to everyone's PHP programming based on the Zend Framework framework.