Zend Framework数据库操作技巧总结

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

本文实例总结了Zend Framework数据库操作。,具体如下:

Zend_Db数据库知识

例子:

Model文件:

$this->fetchAll("is_jian=1","id DESC",0,2)->toArray();
//根据is_jian=1,按id倒序排列取前2条记录当第一个参数为null时,则直接按id倒序排列ASC为正序。

路由文件:

$video=new Video();//实例化数据库类
$this->view->get2Video =$video->get2Video();//取到2条首页推荐的数据

index.phtml文件:

<?php foreach ($this->get2Video as $video): ?>
<?=$video['id']; ?>
<?=$video['name']; ?>
<? endforeach; ?>

添加引号防止数据库攻击

quote用法

$value = $db->quote('St John"s Wort');
// $value 现在变成了 '"St John"s Wort"' (注意两边的引号)
// 为数组加引号
$value = $db->quote(array('a', 'b', 'c'));
// $value 现在变成了 '"a", "b", "c"' (","分隔的字符串)

quoteInto用法

echo $where = $db->quoteInto('id = ?', 1);
// $where 现在为 'id = "1"' (注意两边的引号)
// 在where语句中为数组加上引号
$where = $db->quoteInto('id IN(?)', array(1, 2, 3));
// $where 现在为 'id IN("1", "2", "3")' (一个逗号分隔的字符串)

(1)数据查询总结

直接进行查询.    ( 使用完整的sql语句)

//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);
// 使用PDOStatement对象$result将所有结果数据放到一个数组中
$videoArray = $result->fetchAll();

fetchAll用法

fetchAll($where = null, $order = null, $count = null, $offset = null)

取回结果集中所有字段的值,作为连续数组返回,如果参数不设置就写成null

可以取回结果集的指定条数

$videoArray=$this->fetchAll("is_jian=1 and is_guo=1","id DESC",0,2)->toArray();

fetchAssoc用法

fetchAssoc($sql, $bind = array())

取回结果集中所有字段的值,作为关联数组返回, 第一个字段作为码

$db = $this->getAdapter();
$videoArray=$db->fetchAssoc("SELECT * FROM m_video WHERE `is_jian` = :title",array('title' => '1'));

fetchCol用法

fetchCol($sql, $bind = array())

取回所有结果行的第一个字段名

$db = $this->getAdapter();
$videoArray=$db->fetchCol("SELECT name FROM m_video WHERE `is_jian` = :title",array('title' => '1'));

fetchOne用法

fetchOne($sql, $bind = array())

只取回第一个字段值

相关文章 大家在看