SoFunction
Updated on 2025-03-09

Summarize Zend Framework database operation skills

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-&gt;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-&gt;quote(array('a', 'b', 'c'));
// $value now becomes '"a", "b", "c"' ("," separated string)

quoteInto usage

echo $where = $db-&gt;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-&gt;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-&gt;getAdapter();
$sql = $db-&gt;quoteInto('SELECT * FROM `m_video` WHERE `is_guo` =?', '1');
$result = $db-&gt;query($sql);
// Use PDOStatement object $result to put all the result data into an array$videoArray = $result-&gt;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-&gt;getAdapter();
$result = $db-&gt;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-&gt;fetch()) {
//  echo $row['name'];
//}
//$rows = $result-&gt;fetch();
//$rows = $result-&gt;fetchAll();
//$obj = $result-&gt;fetchObject();//echo $obj-&gt;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-&gt;getAdapter();
$select = $db-&gt;select();
$select-&gt;from('m_video', array('id','name','clicks'))
-&gt;where('is_guo = :is_guo and name = :name')
-&gt;order('name')// By what sort of columns, participate as an array (multiple fields) or a string (one field)-&gt;group()//Group-&gt;having()//Conditions for grouping query data-&gt;distinct()// No parameters, remove duplicate values.  Sometimes the same result as groupby returns-&gt;limit(10);
// Use bound parameters to read the result$params = array('is_guo' =&gt; '1','name'=&gt;'The 12 Zodiac Signs');
//$sql = $select->__toString();//Get the query statement for debugging$result = $db-&gt;fetchAll($select,$params);
implementselectQuery
$stmt = $db-&gt;query($select);
$result = $stmt-&gt;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-&gt;getAdapter();
$select = $db-&gt;select();
$select-&gt;from('m_video', array('id','name','pic','actor','type_id','up_time'))
-&gt;where('is_guo = :is_guo and is_jian = :is_jian')
-&gt;order('up_time')
-&gt;limit(2);
$params = array('is_guo' =&gt; '1','is_jian'=&gt;'1');
$select-&gt;join('m_type', 'm_video.type_id = m_type.t_id', 'type_name');//Multi-table joint query$videoArray = $db-&gt;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-&gt;getAdapter();
$where = $db-&gt;quoteInto('name = ?', 'ccc');// Where conditional statement for deleting dataecho $rows_affected = $db-&gt;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-&gt;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-&gt;getAdapter();
$set = array (
'name' =&gt; 'Butterfly shadows',
'clicks' =&gt; '888',
);
$where = $db-&gt;quoteInto('id = ?', '10');// where statement// Update table data and return the updated number of rowsecho $rows_affected = $db-&gt;update($table, $set, $where);

The second method: Only update the

$set = array (
'name' =&gt; 'Butterfly shadows are heavy 22',
'clicks' =&gt; '8880',
);
$db = $this-&gt;getAdapter();
$where = $db-&gt;quoteInto('id = ?', '10');// where statement$rows_affected = $this-&gt;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-&gt;getAdapter();
// Construct the insert array in the format of "column name" => "data" and insert the data rows$row = array (
'title'   =&gt; 'Hello everyone.  111',
'content' =&gt; 'The film and television network needs to be developed using zend framework',
'time' =&gt; '2009-05-04 17:23:36',
);
// Insert data rows and return the number of inserted rows$rows_affected = $db-&gt;insert($table, $row);
// The last data idecho $last_insert_id = $db-&gt;lastInsertId();
$row=array(
'name'=&gt;'curdate()',
'address' =&gt; 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-&gt;getAdapter();
$db-&gt;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'=&gt;null,
'title'   =&gt; 'Hello everyone.  111',
'content' =&gt; 'The film and television network needs to be developed using zend framework',
'time' =&gt; '2009-05-04 17:23:36',
);
try {
// Insert data rows and return the number of inserted rows$rows_affected = $db-&gt;insert($table, $row);
// The last data id$last_insert_id = $db-&gt;lastInsertId();
$db-&gt;commit();// Transaction submission}catch (Exception $e){
$db-&gt;rollBack();
echo 'Catch exception:'.$e-&gt;getMessage();//Exception message is displayed}
echo $last_insert_id;

(6)Others

$db = $this-&gt;getAdapter();
$tables = $db-&gt;listTables(); // List all tables in the current database$fields = $db-&gt;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.