Zend Framework数据库操作技巧总结

2019-05-02 00:56:23王旭

find()方法,可以使用主键值在表中检索数据.

// 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)数据删除总结

第一种方法:可以删任意表

//quoteInto($text, $value, $type = null, $count = null)
$table = 'm_video';// 设定需要删除数据的表
$db = $this->getAdapter();
$where = $db->quoteInto('name = ?', 'ccc');// 删除数据的where条件语句
echo $rows_affected = $db->delete($table, $where);// 删除数据并得到影响的行数

第二种方法:只能删除本表中的

//delete用法
// delete($where)
$where = "name = 'bbb'";
echo $this->delete($where);// 删除数据并得到影响的行数

(3)数据更新总结

第一种方法:可以更新任意表

// 以"列名"=>"数据"的格式构造更新数组,更新数据行
$table = 'm_video';// 更新的数据表
$db = $this->getAdapter();
$set = array (
'name' => '蝶影重重',
'clicks' => '888',
);
$where = $db->quoteInto('id = ?', '10');// where语句
// 更新表数据,返回更新的行数
echo $rows_affected = $db->update($table, $set, $where);

第二种方法:只能更新本表中的

$set = array (
'name' => '蝶影重重22',
'clicks' => '8880',
);
$db = $this->getAdapter();
$where = $db->quoteInto('id = ?', '10');// where语句
$rows_affected = $this->update($set, $where);// 更新表数据,返回更新的行数

(4)数据插入总结

第一种方法:可以在任意表中插入数据

$table = 'm_gao';// 插入数据的数据表
$db = $this->getAdapter();
// 以"列名"=>"数据"的格式格式构造插入数组,插入数据行
$row = array (
'title'   => '大家好。111',
'content' => '影视网要改成用zend framework开发啊',
'time' => '2009-05-04 17:23:36',
);
// 插入数据行并返回插入的行数
$rows_affected = $db->insert($table, $row);
// 最后插入的数据id
echo $last_insert_id = $db->lastInsertId();
$row=array(
'name'=>'curdate()',
'address' => new Zend_Db_Expr ('curdate()')
)

这样子字段name会插入一个curdate()的字符串,而address插入一个时间值(curdate()的结果2009-05-09)

第二种方法:只能适合本表中的还没有总结出来

(5)事务处理

$table = 'm_gao';// 插入数据的数据表
$db = $this->getAdapter();
$db->beginTransaction();//Zend_Db_Adapter会回到自动commit模式下,直到你再次调用 beginTransaction()方法
// 以"列名"=>"数据"的格式格式构造插入数组,插入数据行
$row = array (
'id'=>null,
'title'   => '大家好。111',
'content' => '影视网要改成用zend framework开发啊',
'time' => '2009-05-04 17:23:36',
);
try {
// 插入数据行并返回插入的行数
$rows_affected = $db->insert($table, $row);
// 最后插入的数据id
$last_insert_id = $db->lastInsertId();
$db->commit();// 事务提交
}catch (Exception $e){
$db->rollBack();
echo '捕获异常:'.$e->getMessage();//打出异常信息
}
echo $last_insert_id;

								 
			 
相关文章 大家在看